如何从dropdownlistfor中获取选定的值

时间:2015-04-09 17:42:13

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

我从模型绑定了dropdownlist,但无法从下拉列表中获取所选值,它显示错误:

  
    

价值' 1'提交表格时无效,

  

型号代码

[Display(Name="User Type")]
[Required(ErrorMessage = "Select user type")]
public List<SelectListItem> usertype { get; set; }

查看代码

@Html.DropDownListFor(m => m.usertype, Model.usertype, new {  @class="form-control input-lg"})

控制器代码

//controller
[HttpPost]
public ActionResult Register(Register register,FormCollection form)
{
}

填充下拉列表

[HttpGet]
public ActionResult Register()
{
    var model=new Register();
    List<string> stState = new List<string>();
    List<SelectListItem> selectListItemStates = new List<SelectListItem>();
    selectListItemStates.Add(new SelectListItem() { Value = string.Empty, Text = "Select State" });
    selectListItemStates.Add(new SelectListItem() { Value = "1", Text = "Mentor" });
    selectListItemStates.Add(new SelectListItem() { Value = "1", Text = "Employee" });
    selectListItemStates.Add(new SelectListItem() { Value ="1", Text = "Finance" });


    model.usertype = selectListItemStates.ToList();
    return View(model);
}

1 个答案:

答案 0 :(得分:2)

您需要在Model for SelectedValue中添加一个最可能为int的属性。

目前您绑定了DropDownListForSelectList不正确,DropDownListFor将发布所选的单个值,通常为整数:

    public List<SelectListItem> usertype { get; set; }

    [Display(Name="User Type")]
    [Required(ErrorMessage = "Select user type")]
    public int UserType { get; set; }

并在视图中:

@Html.DropDownListFor(m=>m.UserType,Model.usertype, new {  @class="form-control input-lg"}