In this article I will explain with an example, how to implement
DropDownList SelectIndexChanged event in
ASP.Net Core (.Net Core 8) Razor Pages.
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; }
}
Index PageModel (Code-Behind)
The PageModel consists of following Handler method.
Handler method for handling GET operation
This Handler method left empty as it is not required.
Handler method for handling POST operation
Inside the Handler Method, the values posted from the Form inside the Page are received through this parameter.
public class IndexModel : PageModel
{
public PersonModel Person { get; set; }
public void OnGet()
{
}
public void OnPostSubmit(PersonModel person)
{
string gender = person.Gender;
}
}
Razor Page (HTML)
HTML Markup
Inside the Razor Page, the ASP.Net TagHelpers is inherited.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Razor Page consists of a
HTML Table, which
Label.
The
Label has been assigned with
asp-for Tag Helper attribute and here also its value is set with the
Gender property which signifies that it is used for displaying the
Model property name.
Then Form consists of an
HTML Table which consists
DropDownList created using
HTML SELECT (DropDownList).
Here, the
Submit Button is hidden as it will be used to Submit the Form when the
DropDownList is
click or
unclick.
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.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model DropDownList_SelectIndexChanged_Core_Razor.Pages.IndexModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post">
<table>
<tr>
<td><label asp-for="Person.Gender"></label></td>
<td>
<select asp-for="Person.Gender" onchange="OnGenderChanged()">
<option value="">Please select</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</td>
</tr>
</table>
<input type="submit" id="btnSubmit" asp-page-handler="Submit" style="display:none" />
</form>
<script type="text/javascript">
function OnGenderChanged() {
document.getElementById("btnSubmit").click();
};
</script>
</body>
</html>
Screenshots
The Form
Values captured in Controller when Form is submitted
Downloads