从asp.net mvc下拉列表中获取值

Jos*_*osh 2 asp.net asp.net-mvc

有人可以帮助我从asp.net mvc的下拉列表中获取值吗?

我可以从文本框等获取值...但是,我如何得到这两件事......

  1. 从控制器类获取选定项目下拉列表的值
  2. 从控制器类获取下拉列表的所有项目列表

谢谢

Dav*_*enn 15

您可以从下拉列表中获取与文本框相同的选定值.

使用默认模型绑定

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
  //MyList will contain the selected value
  //...
}
Run Code Online (Sandbox Code Playgroud)

或者来自FormCollection

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(FormCollection form) {
  string val = form["MyList"];
  //...
}
Run Code Online (Sandbox Code Playgroud)

或者来自请求

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
  string val = Request.Form["MyList"];  //or
  val = Request["MyList"];
  //...
}
Run Code Online (Sandbox Code Playgroud)

您的下拉列表名为"MyList".

<%= Html.DropDownList("MyList", MyItems) %>
Run Code Online (Sandbox Code Playgroud)

或直接的HTML

<select name="MyList">
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
</select>
Run Code Online (Sandbox Code Playgroud)

浏览器只会从下拉列表中提交所选值,而不是所有其他值.要获取所有其他项的列表,您应该首先调用填充列表的代码(假设您使用了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) %>
Run Code Online (Sandbox Code Playgroud)