Hi Shud,
The Session is on the server side so you need to call the server in order to set or retrieve session variables.
You can set your SessionData using jQuery onClick methods.
Check this example. Now please take its reference and correct your code.
Model
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
Controller
Home
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
List<Employee> employees = new List<Employee>();
employees.Add(new Employee { Id = 1, Name = "John Hammond", Country = "United States" });
employees.Add(new Employee { Id = 2, Name = "Mudassar Khan", Country = "India" });
employees.Add(new Employee { Id = 3, Name = "Suzanne Mathews", Country = "France" });
employees.Add(new Employee { Id = 4, Name = "Robert Schidner", Country = "Russia" });
TempData["Employees"] = employees;
return View(employees);
}
}
Default
public class DefaultController : Controller
{
// GET: /Default/
public ActionResult Index()
{
return View();
}
public ActionResult StudentHome(int? id)
{
Session["RegisNo"] = id;
string strReg = Session["RegisNo"].ToString();
return View();
}
}
View
Home
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<_165920_AnchorTag_Pass_Session_MVC.Models.Employee>>" %>
<%@ Import Namespace="_AnchorTag_Pass_Session_MVC.Models" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Index</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('a').on('click', function () {
var id = $(this).attr('name');
$.post("/Default/StudentHome", { id: id }, function (r) {
});
});
});
</script>
</head>
<body>
<div>
<%if (Model != null)
{
foreach (Employee emp in (List<Employee>)TempData["Employees"])
{ %>
<a href="#" name=' <%: emp.Id %>'>
<%: emp.Name %></a>
<br />
<% }
} %>
</div>
</body>
</html>
Default
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
</div>
</body>
</html>
Screenshot