In this article I will explain with an example, how to save TextBox value in Session in ASP.Net Core MVC.
Note: For enabling and configuring Session in ASP.Net Core, please refer my article Enable Session in ASP.Net Core.
 
 

Namespaces

You will need to import the following namespace.
using Microsoft.AspNetCore.Http;
 
 

Controllers

The Controller consists of the following Action methods.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
 

Action method for handling POST operation

Inside this action 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,
Then, the value set in Session object is get using the GetString method of the HttpContext.Session property.
Finally, the View is returned.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Index(string name)
    {
        HttpContext.Session.SetString("Name", name);
        string personName HttpContext.Session.GetString("Name");
        return View();
    }
}
 
 

View

The View consists of an HTML Form which has been created using the following TagHelpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Inside the HTML Form, there is an HTML Table consisting of a TextBox field created for capturing name and a Submit Button.
@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" asp-controller="Home" asp-action="Index">
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="name" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Submit" name="Submit" /></td>
            </tr>
        </table>
    </form>
</body>
</html>
 
 

Screenshot

ASP.Net Core: Save TextBox Value in Session
 
 

Downloads