In this article I will explain with an example, how to use
DropDownList SelectIndexChanged event in
ASP.Net Core (.Net Core 8) 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 IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult 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 and ASP.Net TagHelpers is inherited.
The View consists of an
HTML Form which has been created using the following
TagHelpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form also consists of a
HTML Table, which consists
Label.
Label - Created using Html.LabelFor for displaying text.
Then Form consists of an
HTML Table which consists
DropDownList created using HTML SELECT (DropDownList).
Finally, HTML SELECT (
DropDownList) has been assigned with an
onchange event handler, and when the
option value is
click or
unclick, a
JavaScript function
OnGenderChanged submits the Form and in turn calls the Controller’s Action method.
@model DropDownList_OnChange_MVC_Core.Models.PersonModel
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form asp-action="Index" asp-controller="Home" method="post" id="Form1">
<table>
<tr>
<td><label asp-for="Gender"></label></td>
<td>
<select asp-for="Gender" onchange="OnGenderChanged()">
<option value="">Please select</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</td>
</tr>
</table>
</form>
<script>
function OnGenderChanged() {
document.getElementById("Form1").submit();
};
</script>
</body>
</html>
Screenshots
The Form
Values captured in Controller when Form is submitted
Downloads