Example 1: How to set the value to be selected in the dropdownlist in mvc
BY LOVE
• Here , Model is a dynamic object and from that modal we are fetching States property which is of list type.
• Here , employee is an employee object and from that object we are fetching state property of that particular employee.
@foreach (var S in Model.States)
{
if (S.StateName == employee.State)
{
}
else
{
}
}
Example 2: How to set the value to be selected in the dropdownlist in mvc
• Here , Model is a dynamic object and from that modal we are
fetching States property which is of list type.
• Here , employee is an employee object and from that object
we are fetching state property which is of string type.
@foreach (var S in Model.States)
{
if (S.StateName == employee.State)
{
}
else
{
}
}
Example 3: how to use dropdownlist in mvc
BY LOVE
1- Create a simple method to get the dropdown value
public List GetCategories()
{
var ResultCategory = objRKMGEntities.Categories.ToList();
List listCategories = new List();
foreach (var items in ResultCategory)
{
listCategories.Add(new SelectListItem() { Text = items.Category_Name, Value = items.Category_Id.ToString() });
}
return listCategories;
}
2- Call the GetCategories() in action method and store the data in viewbag.
public ActionResult SubCategory()
{
ViewBag.Categories = GetCategories();
return View();
}
3- Use the viewbag object in the dropdownlist of the view
@Html.DropDownList("CategoryId", ViewBag.Categories as List, "Select Category")