这是模型类的样本
[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")
{
我在这里做了一个选择
错误
答案 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
。