@html.dropdownlist without model
Tutorial Populate ASP.NET MVC Dropdownlist with ViewBag and Model valuesLast Updated: June 7, 2021Sometimes it our ASP.NET MVC application it becomes necessary to populate dropdown with dynamic values such as from the database. So here in the controller you can create a list object of type SelectListItem, fill it with values and then send this object to the View. Show Binding DropDownList with ViewBagLets take a simple example of filling a dropdown list with different states of America. In the controllers action create a list object of type SelectListItem, add some items to it. Finally send this list object to the View using a ViewBag object. Check the below code: Controller public ActionResult Index()
{
List View In the View I simply bind the DropDownList with the ViewBag variable. In this way the dropdownlist gets populated with the dynamic values returned from the controllers action method. Remember that by using jQuery Validation you can perform client side validation of dropdownlist controls easily. Binding DropDownList from ModelSuppose I have to bind DropDownList from the Model which in my case is the marks of a student in different subjects. Model So add a Model class called Marks.cs with the following code. public class Marks
{
public string subject { get; set; }
public int marks { get; set; }
public Marks(string subjectVal, int marksVal)
{
subject = subjectVal;
marks = marksVal;
}
}
Related tutorial How to send HTML Emails with Attachments in ASP.NET MVC Controller In the controller create an array of Model Class object and return it to View. public ActionResult Index()
{
Marks marks = new Marks[] { new Marks("English", 98), new Marks("Maths", 92), new Marks("Science", 83), new Marks("Physics", 99) };
return View(marks);
}
View In the View simply use the Html.DropDownListFor() helper. In its second parameter pass a SelectList object that should contain 3 things:
@Html.DropDownListFor(m => m.marks, new SelectList(Model.marks, "marks", "subject"))
Note: Use .Concat() method to add initial value (Text=All & Value=All) to dropdownlist like: @Html.DropDownListFor(m => m.marks, new List Binding DropDownList from Model ListYou can also pass List of class objects to the View and bind the DropDownList with them. In the same example I can create a List object in the action method and return it to the View. public ActionResult Index()
{
List Finally in the View do like this: @model List I have written 2 very useful tutorial on Validation in ASP.NET MVC. You should check them: 1. Server Side Validation in ASP.NET Core 2. Client Side Validation in ASP.NET Core |