asp.net-mvc 回发后如何保持下拉列表选定的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6981698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to keep dropdownlist selected value after postback
提问by user685254
In asp.net mvc3 how to keep dropdown list selected item after postback.
在asp.net mvc3 中如何在回发后保持下拉列表选中的项目。
回答by Mr A
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"])%>
回答by bjareczek
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");
}
回答by Matthew Abbott
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 DropDownListFormethod, 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 的模型绑定将负责将数据读取到模型中,您只需要确保将其传递回视图以再次显示相同的值。
回答by yoozer8
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 或未选择任何内容)。在视图中,检查值,如果它不为空,则选择适当的选项。
回答by Danilo Silva
Use HttpRequestBase object. In the view, this should work:
使用 HttpRequestBase 对象。在看来,这应该有效:
@Html.DropDownList("mydropdown", ViewBag.Itens as IEnumerable<SelectListItem>, new { value = Request["mydropdown"] })
回答by Eman Abbas
If you are building the drop down list data source in the controller Action Method you can send the selected value to it
如果您在控制器 Action Method 中构建下拉列表数据源,则可以将选定的值发送给它
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" })

