代码之家  ›  专栏  ›  技术社区  ›  James Santiago

从MVC中的FormCollection获取所选下拉列表值

  •  9
  • James Santiago  · 技术社区  · 14 年前

    我有一个表单发布到MVC的一个操作。我要从操作中的FormCollection中提取所选下拉列表项。我该怎么做?

    我的HTML表单:

    <% using (Html.BeginForm())
        {%>
        <select name="Content List">
        <% foreach (String name in (ViewData["names"] as IQueryable<String>)) { %>
              <option value="<%= name %>"><%= name%></option>
        <% } %>
        </select>
        <p><input type="submit" value="Save" /></p>
    <% } %>
    

    我的行动:

    [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        //how do I get the selected drop down list value?
        String name = collection.AllKeys.Single();
        return RedirectToAction("Details", name);
    }
    
    1 回复  |  直到 14 年前
        1
  •  10
  •   Darin Dimitrov    14 年前

    从给你 select 标记有效 name . 有效名称不能包含空格。

    <select name="contentList">
    

    然后从表单参数集合中提取所选值:

    var value = collection["contentList"];
    

    或者更好:不要使用任何集合,使用与所选对象名称同名的操作参数,并保留默认的模型绑定器填充它:

    [HttpPost]
    public ActionResult Index(string contentList)
    {
        // contentList will contain the selected value
        return RedirectToAction("Details", contentList);
    }