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.
- <!--Start of ISActive-->
- <div class="form-group">
- <div class="control-label col-md-5"><b>Publish Menu</b></div>
- <div class="col-md-7">
- @Html.DropDownListFor(modal => modal.IsActive, new List<SelectListItem>{
- new SelectListItem() {Text = "Don't Publish Now", Value= "False"},
- new SelectListItem() {Text = "Publish Now", Value= "True"} },
- new { @class = "form-control" })
- @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text- danger" })
- </div>
- </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
- public ActionResult AddNewPage()
- {
- ViewData["ParentPage"] = new SelectList(db.Pages.AsEnumerable(), "Id", "PageName");
- return View();
- }
Razor code to display dropdown
- <div class="form-group">
- <div class="control-label col-md-5"><b>Parent</b></div>
- <div class="col-md-7">
- @Html.DropDownList("ParentPageID", (SelectList)ViewBag.ParentPage, new { @id = "ParentPageID", @class = "form-control" })
- </div>
- </div>
- </div>
Output