Wednesday, 30 August 2017

Binding static dropdown list with model in mvc3/mvc4 razor

@{
  var listItems = new List<ListItem> { new ListItem { Text = "Single", Value = "Single" }, new ListItem { Text = "Married", Value = "Married" }, new ListItem { Text = "Divorse", Value = "Divorse" } };
  }
  @Html.DropDownListFor(model => model.EmployeeDetail.MaritalStatus, new SelectList(listItems), "-- Select Status --")

Above code is placed in view only.
First what I did is that I made list of listitems (Here I have used example of marital status)

var listItems = new List<ListItem> { new ListItem { Text = "Single", Value = "Single" }, new ListItem { Text = "Married", Value = "Married" }, new ListItem { Text = "Divorse", Value = "Divorse" } };
After this I have just passed this list to @Html.Dropdownlistfor where model & list are bidden.
@Html.DropDownListFor(model => model.EmployeeDetail.MaritalStatus, new SelectList(listItems), "-- Select Status --")
Like this you can bind your static list with model.
If model has any default value then it will be selected in drop down & also when we will select any value in drop down then we can get this value from model in controller.

No comments:

Post a Comment

React Hooks - custom Hook

  v CustomHook Ø React allows us to create our own hook which is known as custom hook. Example – 1 localStorage Demo Step-1 Create ...