Dropdown In ASP.NET MVC

There are a few scenarios where we need to create a dropdown in ASP.NET MVC Razor view.

To bind the static items in the DropDownList, follow the code given below.

  1.                       <!--Start of ISActive-->  
  2.                         <div class="form-group">  
  3.                             <div class="control-label col-md-5"><b>Publish Menu</b></div>  
  4.                             <div class="col-md-7">  
  5.                                 @Html.DropDownListFor(modal => modal.IsActive, new List<SelectListItem>{  
  6.                                 new SelectListItem() {Text = "Don't Publish Now", Value= "False"},  
  7.                                 new SelectListItem() {Text = "Publish Now", Value= "True"} },  
  8.                                 new { @class = "form-control" })  
  9.                                 @Html.ValidationMessageFor(model => model.IsActive, ""new { @class = "text-                                       danger" })  
  10.                             </div>  
  11.                         </div>  
Output



In case the requirement is to bind the DropDownList items from the action method of the controller, we need to set the items collection into ViewBag and use it as a source code.

Controller action method code

  1.         public ActionResult AddNewPage()  
  2.         {  
  3.             ViewData["ParentPage"] = new SelectList(db.Pages.AsEnumerable(), "Id""PageName");  
  4.             return View();  
  5.         }  
Razor code to display dropdown
  1. <div class="form-group">  
  2.   <div class="control-label col-md-5"><b>Parent</b></div>  
  3.     <div class="col-md-7">  
  4.       @Html.DropDownList("ParentPageID", (SelectList)ViewBag.ParentPage, new { @id = "ParentPageID", @class = "form-control" })  
  5.     </div>  
  6.   </div>  
  7. </div>  
Output