【发布时间】:2011-08-08 11:54:54
【问题描述】:
在asp.net mvc3中如何在回发后保留下拉列表中的选定项。
【问题讨论】:
标签: asp.net-mvc
在asp.net mvc3中如何在回发后保留下拉列表中的选定项。
【问题讨论】:
标签: asp.net-mvc
做这样的事情:
[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();
}
在视图中:
<%: Html.DropDownListFor(model => model.ProductID, (SelectList)ViewData["dropdownlist"])%>
【讨论】:
更简单的是,您可以在 ActionResult 输入参数中包含下拉列表的名称。您的下拉菜单应该在表单标签中。当 ActionResult 被发布到时,ASP.Net 将遍历查询字符串、表单值和 cookie。只要您包含下拉列表名称,就会保留选定的值。
这里我有一个包含 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");
}
【讨论】:
MVC 不使用 ViewState,这意味着您需要自己管理值持久性。通常这是通过您的模型完成的。所以,假设你有一个视图模型,例如:
public class MyViewModel { }
还有你的控制器:
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");
}
}
现在,当您将模型与数据一起传回视图时(可能不正确 - 验证失败),当您使用 DropDownListFor 方法时,只需传入值即可:
@Model.DropDownListFor(m => m.Whatever, new SelectList(...))
...等等
MVC 的模型绑定将负责将数据读取到模型中,您只需确保将其传递回视图以再次显示相同的值。
【讨论】:
假设所选项目是帖子的一部分,控制器现在知道它是什么。只需在 ViewData 字典中有一个条目,指示应选择哪个项目(获取时为 null 或未选择任何内容)。在视图中,检查该值,如果它不为空,请选择相应的选项。
【讨论】:
使用 HttpRequestBase 对象。 在视图中,这应该有效:
@Html.DropDownList("mydropdown", ViewBag.Itens as IEnumerable<SelectListItem>, new { value = Request["mydropdown"] })
【讨论】:
如果您在控制器的 Action Method 中构建下拉列表数据源,您可以将选定的值发送给它
控制器:
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();
}
查看:
//ServiceList is coming from ViewBag
@Html.DropDownList("ServicesList", null, htmlAttributes: new { @class = "form-control" })
【讨论】: