Dropdownlist值总是在asp.net mvc中返回零

时间:2017-12-06 16:47:03

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

这是模型类的样本

[Required(ErrorMessage = "Department is required")]
[Display(Name = "Department")]
public int SelectedValue { get; set; }


[Required(ErrorMessage = "Department is required")]
[Display(Name = "Department")]
public List<Department> RoleList { get; set; }

这是视图

<div class="col-md-10">
    @Html.DropDownListFor(m => m.RoleList, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })
    @Html.ValidationMessageFor(model => model.SelectedValue, "",new { @class = "text-danger"})
</div>

列表从数据库中完美填充。现在,当我选择列表中的项目时,必须将选择值发送到控制器

public async Task<ActionResult> Register(RegisterViewModel model)
{
    int Selectedvalue = model.SelectedValue;
    if (ModelState.IsValid && (model.SelectedValue).ToString() != "0")
    {

我在这里做了一个选择

enter image description here

错误

enter image description here

1 个答案:

答案 0 :(得分:3)

你应该改变它

@Html.DropDownListFor(m => m.RoleList, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })

@Html.DropDownListFor(m => m.SelectedValue, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })

DropDownListFor的第一个参数应该是模型中的选择值。在您的情况下,此属性为Model.SelectedValue而非Model.RoleList