C# Programming: How to make DropDownList in ASP.NET MVC

Thursday, August 18, 2016

How to make DropDownList in ASP.NET MVC

Welcome to asp.net Tutorial on how to make dropdown list in asp.net mvc. You are at absolutely right place to start. Lets move on to see how to solve it.
 We are making dropdownlist in a View. i.e Home/Index.cshtml
At first create a SelectListItem

@{ 

    List<SelectListItem> daysList = new List<SelectListItem>();

    daysList.Add(new SelectListItem { Text = "Sunday", Value = "0"});

    daysList.Add(new SelectListItem { Text = "Monday", Value = "1" });

    daysList.Add(new SelectListItem { Text = "Tuesday", Value = "2"});

    daysList.Add(new SelectListItem { Text = "Wednesday", Value = "0" });

    daysList.Add(new SelectListItem { Text = "Thursday", Value = "0"});

    daysList.Add(new SelectListItem { Text = "Friday", Value = "0"});

    daysList.Add(new SelectListItem { Text = "Saturday", Value = "0" });


}

Here we are creating list of days to display it in dropdown list. If you like to select sunday as default then use this code.
daysList.Add(new SelectListItem { Text = "Sunday", Value = "0",selected=true});

You can give any text or value as you like, whichever you need later. Now Let's create DropDownList in our page.
<h1>Select Day</h1>
@Html.DropDownList("Days", daysList, "Select Day")

This Completes our task on making dropdownlist. If you are still confused then you can watch this video too. Thanks.





No comments:

Post a Comment