Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MVC 5:下拉值作为控制器方法的参数_C#_Asp.net Mvc_Razor_Asp.net Mvc 5 - Fatal编程技术网

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)