0

我在 GET 表单中有一个下拉菜单。当用户点击提交时,他们将被定向到同一页面并再次显示表单。我希望用户在已选择的最后一页中显示的下拉选项。例如:

 @Html.DropDownList("Type", null, "Type", new { @class = "sbox-input" } )

website.com/Search?Type="牛肉"

<select name="Type">
   <option value="Fish" >Fish</option>
   <option value="Chicken" >Chicken</option>
   <option value="Beef" selected="selected">Beef</option>
</select>

jQuery 解决方案也可以。

4

1 回答 1

1

只要您在 Action 中有type参数,我认为您不需要 javascript 来执行此操作。我假设你有这样的事情:

public ActionResult Search(string type, [other parameters])
{
    ....
    ViewBag.SearchType = type; // put the selected type to the ViewBag
}

SelectListselectedValue其作为构造函数的第四个参数,因此您可以DropDownList使用所选值在视图中轻松创建:

@Html.DropDownList("Type", new SelectList(new Dictionary<string, string> { { "Fish", "Fish" }, { "Chicken", "Chicken" }, { "Beef", "Beef" } }, "Key", "Value", ViewBag.SearchType))

当然你可以SelectList在 Action 中创建并传递给 View:

public ActionResult Search(string type, [other parameters])
{
    ....
    ViewBag.SearchTypeList = new SelectList(new Dictionary<string, string> { { "Fish", "Fish" }, { "Chicken", "Chicken" }, { "Beef", "Beef" } }, "Key", "Value", type); // you can assign this to the property of your ViewModel if you have one
}

然后在视图中

@Html.DropDownList("Type", ViewBag.SearchTypeList)
于 2012-12-17T11:01:23.720 回答