如何在回发后保持dropdownlist选择的值

时间:2023-01-19 10:27:06

In asp.net mvc3 how to keep dropdown list selected item after postback.

在asp.net mvc3中如何在回发后保持下拉列表选中项目。

6 个解决方案

#1


2  

Do something Like this :

做这样的事情:

[HttpPost]
    public ActionResult Create(FormCollection collection)
    {  if (TryUpdateModel(yourmodel))
            { //your logic 
              return RedirectToAction("Index");
            }
          int selectedvalue = Convert.ToInt32(collection["selectedValue"]);
           ViewData["dropdownlist"] = new SelectList(getAllEvents.ToList(), "EventID", "Name", selectedvalue);// your dropdownlist
            return View();
     }

And in the View:

并在视图中:

 <%: Html.DropDownListFor(model => model.ProductID, (SelectList)ViewData["dropdownlist"])%>

#2


2  

Even easier, you can include the name(s) of your dropdowns in your ActionResult input parameters. Your dropdowns should be in form tags. When the ActionResult is posted to, ASP.Net will iterate through querystrings, form values and cookies. As long as you include your dropdown names, the selected values will be preserved.

更简单的是,您可以在ActionResult输入参数中包含下拉列表的名称。您的下拉列表应该是表单标签。当ActionResult发布到时,ASP.Net将遍历查询字符串,表单值和cookie。只要包含下拉列表名称,就会保留选定的值。

Here I have a form with 3 dropdowns that posts to an ActionResult. The dropdown names are (non-case sensitive): ReportName, Year, and Month.

在这里,我有一个包含3个下拉列表的表单,发布到ActionResult。下拉列表名称(不区分大小写):ReportName,Year和Month。

    //MAKE SURE TO ACCEPT THE VALUES FOR REPORTNAME, YEAR, AND MONTH SO THAT THEY PERSIST IN THE DROPDOWNS EVEN AFTER POST!!!!
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ReportSelection(string reportName, string year, string month)
    {
        PopulateFilterDrowdowns();
        return View("NameOfMyView");
    }

#3


1  

MVC does not use ViewState, which means you will need to manage the value persistence yourself. Typically this is done through your model. So, given that you have a view model, e.g.:

MVC不使用ViewState,这意味着您需要自己管理值持久性。通常,这是通过您的模型完成的。所以,鉴于你有一个视图模型,例如:

public class MyViewModel { }

And your controller:

而你的控制器:

public class MyController : Controller 
{
    public ActionResult Something()
    {
        return View(new MyViewModel());
    }

    public ActionResult Something(MyViewModel model)
    {
        if (!ModelState.IsValid)
            return View(model);

        return RedirectToAction("Index");
    }
}

Now, when you pass the model back to the view with data (probably incorrect - failed validation), when you use your DropDownListFor method, just pass in the value:

现在,当您使用数据(可能不正确 - 验证失败)将模型传递回视图时,当您使用DropDownListFor方法时,只需传入值:

@Model.DropDownListFor(m => m.Whatever, new SelectList(...))

... etc.

MVC's model binding will take care of the reading of the data into your model, you just need to ensure you pass that back to the view to show the same value again.

MVC的模型绑定将负责将数据读入模型,您只需确保将其传递回视图以再次显示相同的值。

#4


0  

Assuming the selected item is part of the post, the controller now knows what it is. Simply have an entry in the ViewData dictionary indicating which item should be selected (null on get or if nothing was selected). In the view, check the value and if it's not null, select the appropriate option.

假设所选项目是帖子的一部分,控制器现在知道它是什么。只需在ViewData字典中有一个条目,指示应该选择哪个项目(获取时为null或者未选择任何内容)。在视图中,检查值,如果它不为null,请选择适当的选项。

#5


0  

Use HttpRequestBase object. In the view, this should work:

使用HttpRequestBase对象。在视图中,这应该工作:

 @Html.DropDownList("mydropdown", ViewBag.Itens as IEnumerable<SelectListItem>, new { value = Request["mydropdown"] })

#6


0  

If you are building the drop down list data source in the controller Action Method you can send the selected value to it

如果要在控制器操作方法中构建下拉列表数据源,则可以将选定的值发送给它

Controller:

 public ActionResult Index( int serviceid=0)
            {


             // build the drop down list data source
                List<Service> services = db.Service.ToList();
                services.Insert(0, new Service() { ServiceID = 0, ServiceName = "All" });
               // serviceid is the selected value you want to maintain
                ViewBag.ServicesList = new SelectList(services, "ServiceID", "ServiceName",serviceid);

               if (serviceid == 0)
                {
                    //do something
                }
                else
                {
                     // do another thing

                }
                return View();
           }

View:

 //ServiceList is coming from ViewBag
@Html.DropDownList("ServicesList", null, htmlAttributes: new { @class = "form-control" })

#1


2  

Do something Like this :

做这样的事情:

[HttpPost]
    public ActionResult Create(FormCollection collection)
    {  if (TryUpdateModel(yourmodel))
            { //your logic 
              return RedirectToAction("Index");
            }
          int selectedvalue = Convert.ToInt32(collection["selectedValue"]);
           ViewData["dropdownlist"] = new SelectList(getAllEvents.ToList(), "EventID", "Name", selectedvalue);// your dropdownlist
            return View();
     }

And in the View:

并在视图中:

 <%: Html.DropDownListFor(model => model.ProductID, (SelectList)ViewData["dropdownlist"])%>

#2


2  

Even easier, you can include the name(s) of your dropdowns in your ActionResult input parameters. Your dropdowns should be in form tags. When the ActionResult is posted to, ASP.Net will iterate through querystrings, form values and cookies. As long as you include your dropdown names, the selected values will be preserved.

更简单的是,您可以在ActionResult输入参数中包含下拉列表的名称。您的下拉列表应该是表单标签。当ActionResult发布到时,ASP.Net将遍历查询字符串,表单值和cookie。只要包含下拉列表名称,就会保留选定的值。

Here I have a form with 3 dropdowns that posts to an ActionResult. The dropdown names are (non-case sensitive): ReportName, Year, and Month.

在这里,我有一个包含3个下拉列表的表单,发布到ActionResult。下拉列表名称(不区分大小写):ReportName,Year和Month。

    //MAKE SURE TO ACCEPT THE VALUES FOR REPORTNAME, YEAR, AND MONTH SO THAT THEY PERSIST IN THE DROPDOWNS EVEN AFTER POST!!!!
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ReportSelection(string reportName, string year, string month)
    {
        PopulateFilterDrowdowns();
        return View("NameOfMyView");
    }

#3


1  

MVC does not use ViewState, which means you will need to manage the value persistence yourself. Typically this is done through your model. So, given that you have a view model, e.g.:

MVC不使用ViewState,这意味着您需要自己管理值持久性。通常,这是通过您的模型完成的。所以,鉴于你有一个视图模型,例如:

public class MyViewModel { }

And your controller:

而你的控制器:

public class MyController : Controller 
{
    public ActionResult Something()
    {
        return View(new MyViewModel());
    }

    public ActionResult Something(MyViewModel model)
    {
        if (!ModelState.IsValid)
            return View(model);

        return RedirectToAction("Index");
    }
}

Now, when you pass the model back to the view with data (probably incorrect - failed validation), when you use your DropDownListFor method, just pass in the value:

现在,当您使用数据(可能不正确 - 验证失败)将模型传递回视图时,当您使用DropDownListFor方法时,只需传入值:

@Model.DropDownListFor(m => m.Whatever, new SelectList(...))

... etc.

MVC's model binding will take care of the reading of the data into your model, you just need to ensure you pass that back to the view to show the same value again.

MVC的模型绑定将负责将数据读入模型,您只需确保将其传递回视图以再次显示相同的值。

#4


0  

Assuming the selected item is part of the post, the controller now knows what it is. Simply have an entry in the ViewData dictionary indicating which item should be selected (null on get or if nothing was selected). In the view, check the value and if it's not null, select the appropriate option.

假设所选项目是帖子的一部分,控制器现在知道它是什么。只需在ViewData字典中有一个条目,指示应该选择哪个项目(获取时为null或者未选择任何内容)。在视图中,检查值,如果它不为null,请选择适当的选项。

#5


0  

Use HttpRequestBase object. In the view, this should work:

使用HttpRequestBase对象。在视图中,这应该工作:

 @Html.DropDownList("mydropdown", ViewBag.Itens as IEnumerable<SelectListItem>, new { value = Request["mydropdown"] })

#6


0  

If you are building the drop down list data source in the controller Action Method you can send the selected value to it

如果要在控制器操作方法中构建下拉列表数据源,则可以将选定的值发送给它

Controller:

 public ActionResult Index( int serviceid=0)
            {


             // build the drop down list data source
                List<Service> services = db.Service.ToList();
                services.Insert(0, new Service() { ServiceID = 0, ServiceName = "All" });
               // serviceid is the selected value you want to maintain
                ViewBag.ServicesList = new SelectList(services, "ServiceID", "ServiceName",serviceid);

               if (serviceid == 0)
                {
                    //do something
                }
                else
                {
                     // do another thing

                }
                return View();
           }

View:

 //ServiceList is coming from ViewBag
@Html.DropDownList("ServicesList", null, htmlAttributes: new { @class = "form-control" })