In this article I will explain a short tutorial with example, how to display Session value in TextBox in ASP.Net Core MVC.
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, the Session objects are set using the SetString method and the View is returned.
public class HomeController : Controller
{
public IActionResult Index()
{
HttpContext.Session.SetString("Name", "Mudassar Khan");
HttpContext.Session.SetString("Country", "India");
return View();
}
}
View
Inside the View, the IHttpContextAccessor Interface object is injected in order to access the Session and its functions inside the View.
The View consists of two HTML INPUT TextBoxes.
The Session objects are set in the value attribute of INPUT TextBoxes using the GetString method with the help of Razor Syntax.
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor Accessor
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table cellpadding="5">
<tr>
<td>Name:</td>
<td><input type="text" value="@Accessor.HttpContext.Session.GetString("Name")" /></td>
</tr>
<tr>
<td>Country:</td>
<td><input type="text" value="@Accessor.HttpContext.Session.GetString("Country")" /></td>
</tr>
</table>
</body>
</html>
Screenshot
Downloads