如何在MVC3中维护下拉列表的选定值?
我正在使用以下代码创建下拉列表:
<%= Html.DropDownList("PEDropDown",
(IEnumerable<SelectListItem>)ViewData["PEDropDown"],
new { onchange = "this.form.action='/Screener/Screener';this.form.submit();" }
)%>
答案 0 :(得分:1)
以下是我使用的一个例子。我不确定,这是你用来填充DropDownList
的方式<%=Html.DropDownList("ddlCategories", IEnumerable<SelectListItem>)ViewData["PEDropDown"], "CategoryId", "CategoryName", Model.CategoryId), "Select Category", new { onchange = "this.form.action='/Screener/Screener';this.form.submit();"})%>
另一种方法是,在控制器中创建一个选择列表,如下所示
List<SelectListItem> CategoryList = new List<SelectListItem>();
foreach (var item in Categories)
{
CategoryList.Add(new SelectListItem
{
Selected = Model.CategoryId,
Text = item.CategoryName, Value = Convert.ToString(item.CategoryId) });
}
ViewData["PEDropDown"]=CategoryList;
并在视图中使用
<%:Html.DropDownList("ddlCategories",IEnumerable<SelectListItem>)ViewData["PEDropDown"], "CategoryId", "CategoryName", new { onchange = "this.form.action='/Screener/Screener';this.form.submit();"})%>
答案 1 :(得分:0)
我不是100%肯定我得到了你想做的事,但我想你想从下拉列表中得到所选的值?
在那种情况下:
new { onchange = "alert(this.options[this.selectedIndex].value);" }
我现在把它放在警报中,因为我不知道你想用什么做什么
答案 2 :(得分:0)
将值传回控制器,然后在控制器中填充SelectListItem列表:
public actionresult yourmethod (int idToPass)
{
List<SelectListItem> SLIList = new List<SelectListItem>();
foreach (Model model in dropdownList)
{
SelectListItem SLI = new SelectListItem();
SLI.text = model.CategoryName;
SLI.selected = model.CategoryId == idToPass;
SLIList.Add(SLI);
}
ViewData["myDDL"] = SLIList;
}
答案 3 :(得分:0)
你可以试试这个。 使用ViewBag代替ViewData(我建议,最好使用Model对象)
Html.DropDownList("PEDropDown", new SelectList(ViewBag.PEDropDown, "Key", "Value", Model.PEDropDownSelectedValue), new { onchange = "document.location.href = '/ControllerName/ActionMethod?selectedValue=' + this.options[this.selectedIndex].value;" }))
SelectList 中的第四个参数是所选值。必须使用模型对象传递它。 调用特定操作方法时,请将模型对象设置如下。
public ActionResult ActionMethod(string selectedValue)
{
ViewModelPE objModel = new ViewModelPE();
// populate the dropdown, since you lost the list in Viewbag
ViewBag.PEDropDown = functionReturningListPEDropDown();
objModel.PEDropDownSelectedValue = selectedValue;
return View(objModel);
// You may use the model object to pass the list too instead of ViewBag (ViewData in your case)
}