In this article I will explain with an example, how to save
TextBox value in Session in ASP.Net Core Razor Pages.
Namespaces
You will need to import the following namespace.
using Microsoft.AspNetCore.Http;
Razor PageModel (Code-Behind)
The PageModel consists of following Handler methods.
Handler method for handling GET operation
This Handler method is left empty as it is not required.
Handler method for handling POST operation
Inside this Handler method, the Session object is created and a string value is set in the Session object using the SetString method of the HttpContext.Session property.
Finally, the value set in Session object is get using the GetString method of the HttpContext.Session property.
public class IndexModel : PageModel
{
public void OnGet()
{
}
public void OnPostSubmit(string name)
{
HttpContext.Session.SetString("Name", name);
string personName = HttpContext.Session.GetString("Name");
}
}
Razor Page (HTML)
Inside the Razor Page, the ASP.Net TagHelpers is inherited.
The
HTML of Razor Page consists of an
HTML Form.
The Form consisting of an
HTML Table which consists of a TextBoxes field created for capturing name 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.
@page
@model TextBox_Session_Core_Razor.Pages.IndexModel
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" asp-page-handler="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Screenshot
Downloads