从MVC一个的FormCollection获取选定的下拉列表值 [英] Get the selected drop down list value from a FormCollection in MVC

查看:213
本文介绍了从MVC一个的FormCollection获取选定的下拉列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格发布到与MVC的动作。我想拉下拉列表中选择项目从动作的FormCollection。我该怎么做呢?

我的HTML表单:

 <使用%(Html.BeginForm())
    {%GT;
    <选择名称=内容列表>
    <%的foreach(字符串名称(计算机[名称]作为IQueryable的<串GT;)){%GT;
          <期权价值=<%=名称%GT;><%=名称%GT;< /选项>
    <%}%GT;
    < /选择>
    < P><输入类型=提交值=保存/>< / P>
<%}%GT;

我的动作:

  [HttpPost]
公众的ActionResult指数(的FormCollection集合)
{
    //我怎么选定的下拉列表值?
    字符串名称= collection.AllKeys.Single();
    返回RedirectToAction(详细资料,名);
}


解决方案

这是给你的选择标记的有效名称。有效的名称不能包含空格。

 <选择名称=contentList>

,然后从表单参数集合获取所选值:

  VAR值=收藏[contentList];

甚至更好:不使用任何的集合,使用具有相同的名称作为您选择的名称的操作参数,并保留默认的模型绑定来填充它:

  [HttpPost]
公众的ActionResult指数(字符串contentList)
{
    // contentList将包含选定的值
    返回RedirectToAction(详细资料,contentList);
}

I have a form posting to an action with MVC. I want to pull the selected drop down list item from the FormCollection in the action. How do I do it?

My Html form:

<% 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>
<% } %>

My Action:

[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);
}

解决方案

Start by giving your select tag a valid name. A valid name cannot contain spaces.

<select name="contentList">

and then fetch the selected value from the form parameters collection:

var value = collection["contentList"];

Or even better: don't use any collections, use an action parameter which has the same name as the name of your select and leave the default model binder populate it:

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

这篇关于从MVC一个的FormCollection获取选定的下拉列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆