How to get the selected value from the drop-down list for

I am binding a dropdownlist from the model, but I can’t get the selected value from the drop-down list, it shows an error:

The value "1" is invalid, and when submitting the form

Model code

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

View code

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

Controller code

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

Fill in the drop down list

[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);
}
+4
source share
1 answer

You need to add a property to Model for SelectedValue, which may be intmost likely.

You are currently binding DropDownListForto SelectList, which is not right, DropDownListForwill output the selected one value, which is usually an integer:

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

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

and in view:

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

All Articles