【问题标题】:Get the selected drop down list value from a FormCollection in MVC从 MVC 中的 FormCollection 中获取选定的下拉列表值
【发布时间】:2010-06-13 15:56:53
【问题描述】:

我有一个使用 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);
}

【问题讨论】:

    标签: c# html asp.net-mvc-2


    【解决方案1】:

    首先给你的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);
    }
    

    【讨论】:

    • 哦,快!谢谢,这成功了。我尝试了两种方法,但我喜欢你使用 action 参数的方式。
    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 2021-06-05
    相关资源
    最近更新 更多