In this article I will explain with an example, how to submit (post) a Form and send data from Razor Page to
POST Handler method in (.Net Core 8)
Razor Pages.
This article will explain how to create Form Fields and then send data from Razor Page to
POST Handler method using
Model class in (.Net Core 8)
Razor Pages.
Model
The Model class consists of following properties.
public class PersonModel
{
[BindProperty]
public string FirstName { get; set; }
[BindProperty]
public string LastName { get; set; }
}
Razor PageModel (Code-Behind)
The PageModel consists of following Action Handler methods.
Handler method for handling GET operation
This Handler method handles the GET calls, for this particular example it is not required and hence left empty.
Handler method for handling Button Click and POST operation
This Handler method handles the POST call when the Submit Button is clicked and the Form is submitted.
The Handler method for POST operation accepts the values of First Name and Last Name sent from the Razor Page through PersonModel class object received as parameter.
Finally, the values are assigned to the Name property which is later displayed on the Razor Page.
public class IndexModel : PageModel
{
public string Name { get; set; }
public void OnGet()
{
}
public void OnPostSubmit(PersonModel person)
{
this.Name = string.Format("Name: {0} {1}", person.FirstName, person.LastName);
}
}
Razor Page (HTML)
The
HTML of Razor Page consists of an
HTML Form with two
TextBox elements and a
Submit Button.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor
PageModel, the Handler method name is
OnPostSubmit but here it will be specified as
Submit when calling from the Razor
HTML Page.
Finally, the value of the Name property is displayed using Razor syntax.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Razor_Form_Submit.Pages.IndexModel
@{
Layout = null;
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" id="txtFirstName" name="FirstName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="txtLastName" name="LastName" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" asp-page-handler="Submit" /></td>
</tr>
</table>
<hr />
@Model.Name
</form>
</body>
</html>
Screenshot
Downloads