Reputation: 618
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
[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);
}
Upvotes: 4
Views: 1117
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