In this article I will explain with an example, how to use
DropDownList SelectIndexChanged event in
ASP.Net MVC.
Model
The Model class consists of the following property.
public class PersonModel
{
/// <summary>
/// Gets or sets Gender.
/// </summary>
[Display(Name = "Gender:")]
public string Gender { get; set; }
}
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
Inside the Action Method, the values posted from the Form inside the View are received through this parameter.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(PersonModel person)
{
string gender = person.Gender;
return View();
}
}
View
HTML Markup
Inside the View, in the very first line the PersonModel class is declared as model for the View.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The View also consists of an
HTML Form which consists of:
Label - Created using Html.LabelFor for displaying text.
The Form consists of an
HTML Table which consists
DropDownList created using
Html.DropDownListFor Helper methods respectively.
Finally,
ListItem has been assigned with an
onchange event handler, and when the
ListItem is
click or
unclick, a
JavaScript function
OnGenderChanged submits the Form and in turn calls the Controller’s Action method.
@model DropDownList_OnChange_MVC.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "Form1" }))
{
<table cellpadding="0" cellspacing="0">
<tr>
<td>@Html.LabelFor(m => m.Gender)</td>
<td>
@Html.DropDownListFor(m => m.Gender, new List<SelectListItem>
{ new SelectListItem{Text= "Male", Value= "M"},
new SelectListItem{Text= "Female", Value= "F"}}, "Please select", new { @onchange = "OnGenderChanged()" })
</td>
</tr>
</table>
}
<script>
function OnGenderChanged() {
document.getElementById("Form1").submit();
};
</script>
</body>
</html>
Screenshots
The Form
Values captured in Controller when Form is submitted
Downloads