c# – 如何从dropdownlistfor中获取选定的值

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

The value ‘1’ is invalid , while submitting the form

型号代码

[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);
}

最佳答案 您需要在Model for SelectedValue中添加一个属性,该属性最有可能是int.

目前你使用SelectList绑定DropDownListFor是不对的,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"}
点赞