In this article I will explain with an example, how to use Hidden Fields with Razor Pages in ASP.Net Core.
This article will explain how to create Hidden Fields using Model class, set its value and then retrieve data from Razor Page inside POST Handler method in ASP.Net Core.
Model
Following is a Model class named PersonModel with three properties i.e. PersonId, FirstName and LastName.
public class PersonModel
{
[BindProperty]
public int PersonId { get; set; }
[BindProperty]
public string FirstName { get; set; }
[BindProperty]
public string LastName { get; set; }
}
Razor PageModel (Code-Behind)
The PageModel consists of two Action Handler methods.
Handler method for handling GET operation
This Handler method handles the GET calls, the Person property is initialized and the value of the PersonId field is set which will be later assigned to the Hidden Field.
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 receives the values sent from the Razor Pages through the Person property.
public class IndexModel : PageModel
{
[BindProperty]
public PersonModel Person { get; set; }
public void OnGet()
{
this.Person = new PersonModel { PersonId = 1 };
}
public void OnPostSubmit()
{
PersonModel person = this.Person;
}
}
Razor Page (HTML)
The HTML of Razor Page consists of an HTML Form with two TextBox elements, a Hidden Field and a Submit Button.
The PersonId value is assigned to the Hidden Field using the asp-for attribute.
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.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Razor_Hidden_Field_Core.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>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><input type="hidden" id="hfPersonId" name="PersonId" asp-for="Person.PersonId"/></td>
<td><input type="submit" value="Submit" asp-page-handler="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>
Screenshot
Downloads