mayank bisht
mayank bisht

Reputation: 618

How to get selected value from dropdownlistfor

I am binding dropdownlist from model, but am unable to get the selected value from the dropdownlist, it shows error:

The value '1' is invalid , while 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)
{
}

To populate dropdownlist

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

Upvotes: 4

Views: 1117

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

You need to add a property in Model for SelectedValue which can be int most probably.

Currently you are binding DropDownListFor with SelectList which is not right, DropDownListFor will post single value which is selected, which is normally 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"}

Upvotes: 2

Related Questions