Simple DropDown with Select Tag(Text Only)
We can create simple DropDown list by using <select></select> tag of HTML with values like below.
<select name="Author">
<option>Krishna Garad</option>
<option>Vulpes</option>
<option>Arjun</option>
<option>Sonakshi</option>
<option>Monika</option>
Simple DropDown with Select Tag(text as well as value);
In the above we see a simple DropDownList which contains only text, not any value field. To create a DropDown with text as well as value use the following snippet.
<select name="AuthorWithValue">
<option value="100">Krishna Garad</option>
<option value="110">Vulpes</option>
<option value="120">Arjun</option>
<option value="130">Sonakshi</option>
<option value="140">Monika</option>
Simple DropDown Populated From Database(with text only)
In many cases we need our DropDownList to be populated from a database. We can do that by populating the list of strings in our controller and then access each string from the list in our aspx page like below.
In controller
cscEntities entity = new cscEntities();
var x = (from n in entity.Authors select n);
List<string> items = new List<string>();
foreach (var item in x)
{
items.Add(item.Name);
}
ViewBag.Authors = items;
In View
<select name="AuthorFromDB">
<%foreach (var item in ViewBag.Authors)
{%>
<option><%=item%></option>
<%} %>
</select>
DropDownList without Select Tag
We can create a DropDown without using the select tag which is populated from the database like below.
In Controller
var db = new cscEntities();
var query = db.Authors.Select(c => new { c.AuthorId, c.Name });
ViewBag.Authors1 = new SelectList(query.AsEnumerable(), "AuthorId", "Name");
In View
<%= Html.DropDownList("Authors1", (IEnumerable<SelectListItem>)ViewBag.Authors1)%>
DropDown with Default Value
Many times we have a requirement to keep some default values and then populate the DropDown from the database.
<%= Html.DropDownList("Authors1", (IEnumerable<SelectListItem>)ViewBag.Authors1, "--Select Author--")%>
DropDown with Autopostback
Still now we have seen DropDownList creation but an important event of a DropDown we all know i.e. autopostback in ASP.Net application by setting Autopostback true we can make our DropDown capable of doing a post back in MVC we can't. In MVC we can do it in the following way.
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "Form1" }))
{%>
<%= Html.DropDownList("Authors1", (IEnumerable<SelectListItem>)ViewBag.Authors1, "--Select Author--", new { onchange = "document.getElementById('Form1').submit();" })%>
<%} %>
Conclusion
In this way we can use our favorite DropDownList control in ASP.NET MVC application with postback and default values as well as populating from a database.