In this article I will explain with an example, how to pass (send) data from Controller to View using Session in ASP.Net Core MVC.
Namespaces
You will need to import the following namespace.
using Microsoft.AspNetCore.Http;
Controller
The Controller consists of the following two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for displaying the Session object
When the Display Session Button is clicked, SetSession Action method is executed which saves the value to the Session using the SetString method.
Finally, the Action is redirected to the Index Action method.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult SetSession()
{
//Set value in Session object.
HttpContext.Session.SetString("Name", "Mudassar Khan");
return RedirectToAction("Index");
}
}
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 an HTML Form with following ASP.Net Tag Helpers attributes.
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.
The Form consists of a Submit Buttons i.e. for Displaying Session.
The Submit Button has been set with a FormAction attribute which specifies the Action method which will be called when the Submit Button is clicked.
When the Display Session button is clicked, the value from the Session object is displayed using the GetString method.
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor Accessor
@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">
<input type="submit" id="btnSet" formaction="@Url.Action("SetSession")" value="Display Session"/>
<hr/>
Session: @Accessor.HttpContext.Session.GetString("Name")
</form>
</body>
</html>
Screenshot
Downloads