In MVC we have 2 ways to bind the dropdown is strongly type
and nomal way.
There are various ways that you can bind the dropdownlist in
MVC.
1.
Binding Dropdownlist using the view bag in MVC
Binding SelectedList to Dropdown
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = "Male", Value = "Male", Selected = false });
items.Add(new SelectListItem() { Text = "Female", Value = "Female", Selected = true });
SelectList selectList = new SelectList(items, "Value", "Text");
ViewBag.Gender = selectList;
|
Binding it in HTML, like below
@Html.DropDownList("Gender", ViewBag.Gender as SelectList)
|
Will get output as below.
2.
Binding Model to DropdownList in MVC
Model.Gender should be bind from controller
as SelectList
@Html.DropDownList("Gender", Model.Gender)
|
3.
Binding hardcode value to dropdownList in MVC.
@Html.DropDownList("Gender", new List<SelectListItem>
{ new SelectListItem { Text = "Male", Value = "Male", Selected=true},
new SelectListItem { Text = "Female", Value = "Female"},
}, "Select
Gender")
|
Output will look alike.
4.
Binding the Values to dropdownlistfor in MVC.
Controller Code – Function declaration
|
private void BindDropdown(ref RathoreDetailModel rathoreDetails)
{
rathoreDetails.GenderDropDown =
GetGenderDetail();
}
private IEnumerable<DropdownList>
GetGenderDetail()
{
// here you can
get the result from db and frame it to model
return new List<DropdownList> {
new DropdownList(){Value = "Female", Key="F" },
new DropdownList(){Value = "Male", Key="M" }
};
}
|
Controller – Function call
|
BindDropdown(ref lstRathoreDetails);
return View(lstRathoreDetails);
|
CSHTML Code Binding
<div class="form-group">
<label for="Occupation">लिंग</label><span class="text-required">*</span>
@Html.DropDownListFor(model
=> model.Gender, new SelectList(Model.GenderDropDown, "Key", "Value", 0),"--Select Gender--", new { @class = "form-control" })
@Html.ValidationMessageFor(model
=> model.Occupation, "", new { @class = "text-error" })
</div>
|
No comments:
Post a Comment