谁能帮我从 asp.net mvc 的下拉列表中获取值?
我可以从文本框等中获取值...但是,我如何获取这两个东西...
- 从 Controller 类中获取下拉列表的选定项值
- 从 Controller 类中获取下拉列表的所有项目列表
谢谢
最佳答案
您可以像获取文本框一样从下拉列表中获取所选值。
使用默认模型绑定(bind)
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
//MyList will contain the selected value
//...
}
或来自 FormCollection
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(FormCollection form) {
string val = form["MyList"];
//...
}
或来自请求
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
string val = Request.Form["MyList"]; //or
val = Request["MyList"];
//...
}
您的下拉列表名为“MyList”。
<%= Html.DropDownList("MyList", MyItems) %>
或直接 HTML
<select name="MyList">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
浏览器只会提交从下拉列表中选择的值,而不是所有其他值。要获取所有其他项目的列表,您应该首先调用填充列表的代码(假设您使用了 Html.DropDownList())。
更新
[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample() {
ViewData["MyItems"] = GetSelectList();
return View();
}
[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample(string MyList) {
//MyList contains the selected value
SelectList list = GetSelectList(); //list will contain the original list of items
//...
}
private SelectList GetSelectList() {
Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("Item 1", "1");
list.Add("Item 2", "2");
list.Add("Item 3", "3");
return new SelectList(list, "value", "key");
}
//...
<%= Html.DropDownList("MyList", ViewData["MyItems"] as SelectList) %>
关于asp.net - 从 asp.net mvc 下拉列表中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1398196/