Create a drop down in razor view in ASP.NET MVC

How to create a drop down in ASP.NET MVC view?

There are few scenarios when we need to create a dropdown in the ASP.NET MVC Razor view.
To bind static items in the DropDownList 
@Html.DropDownList("dropRoles", new List<SelectListItem>() 
 { 
   new SelectListItem() { Text= "Yes", Value = "true" }, 
   new SelectListItem() { Text= "No", Value = "false", Selected = true } 
 }, "Select ...")

Here, the name of the DropDownList is dropRoles and items will be Yes and No. The first item will be “Select …”.
In case the requirement is to bind the DropDownList items from action method of the Controller, we need to set the items collection into ViewBag and use it as source code.
CONTROLLER ACTION METHOD CODE 
var data = from p in db.PersonalDetails              
                                join f in db.Files                 
                              on p.AutoId equals f.PersonalDetailsId              
                             select new                    
                     {                         
                             PersonName = p.FirstName,       
                         MyFileName = f.FileName   
                     };  
           SelectList list = new SelectList(data, "MyFileName", "PersonName");   
           ViewBag.Roles = list;
VIEW CODE
@Html.DropDownList("MultipleTables", ViewBag.Roles as SelectList) 
Here SelectList instance accepts collection of the object as parameter from which the source of the DropDown to build, the second parameter is the name of the data value field and the third parameter is the text value field that would be used in the item of the DropDownList.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...