维护MVC3下拉列表的状态



如何在MVC3中保持下拉列表的选定值?

我使用以下代码创建下拉列表:

<%= Html.DropDownList("PEDropDown", 
        (IEnumerable<SelectListItem>)ViewData["PEDropDown"], 
        new { onchange = "this.form.action='/Screener/Screener';this.form.submit();" }
)%>

下面是我使用的一个例子。我不确定,这是你用来填充下拉列表

的方式
<%=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();"})%>

我不是100%确定我得到你想做什么,但我假设你想从下拉列表中获得选定的值?

在这种情况下:

new { onchange = "alert(this.options[this.selectedIndex].value);" }

我现在把它放在一个警告中,因为我不知道你要怎么处理

这个值

将值传递回控制器,然后在控制器中填充一个SelectListItems列表:

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;
}

你可以试试这个。使用ViewBag而不是ViewData(我建议,最好使用模型对象)

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)
}

最新更新