C# MVC 5:下拉值作为控制器方法的参数
我正在构建一个带有下拉菜单和提交按钮的简单表单C# MVC 5:下拉值作为控制器方法的参数,c#,asp.net-mvc,razor,asp.net-mvc-5,C#,Asp.net Mvc,Razor,Asp.net Mvc 5,我正在构建一个带有下拉菜单和提交按钮的简单表单 @using(Html.BeginForm("Index", "Account", FormMethod.Post)) { @Html.DropDownList( "Roles", new SelectList(new List<string> { "User", "Manager", "Chuck Norris" }), new { id = "role", name="role
@using(Html.BeginForm("Index", "Account", FormMethod.Post))
{
@Html.DropDownList(
"Roles",
new SelectList(new List<string> { "User", "Manager", "Chuck Norris" }),
new { id = "role", name="role" })
<input type="submit" value="Update" />
}
@使用(Html.BeginForm(“Index”,“Account”,FormMethod.Post))
{
@Html.DropDownList(
“角色”,
新选择列表(新列表{“用户”、“经理”、“Chuck Norris”}),
新的{id=“role”,name=“role”})
}
我的控制器如下所示:
[HttpPost]
public ActionResult Index(string role) <-- role is null when clicking submit
{
}
[HttpPost]
public ActionResult Index(string role)使用name=“Roles”
生成
元素,但方法的参数名为role
(不是复数)。您需要更改其中一个以使它们匹配(请注意,DefaulModelBinder
不区分大小写,因此参数可以是roles
或roles
)`
请注意,设置new{name=“role”}
不会更改由HtmlHelper
方法生成的name
属性。也不必使用name{id=“role”}
-该方法已生成id=“Roles”
,因此如果您使用javascript/jquery引用元素,则只需使用$(#Roles')
作为选择器将角色
更改为角色
,如下面的代码所示
public ActionResult Index(string role)
到
现在它可以使用name=“Roles”
生成
,但是您的参数名为role
(不是复数)。改变一个或另一个。(尝试使用name=“role”
被该方法忽略-幸运的是)这会创建什么样的HTML?@StephenMuecke请回答这个问题,我会接受它。
public ActionResult Index(string Roles)