I have a project in MVC 5 where the user must log in, and with the use of a "Session" variable his name is taken to display it in the header of _Layout.cshtml, this through a @Viewbag.session
, but for some reason it is not working. This is the code:
In the model:
[Serializable]
public class ClsLogin
{
public int idUsuario { get; set; }
[Required]
public string NombreUsuario { get; set; }
[Required]
public string Contrasena { get; set; }
public string SessionValue {get; set; }
}
In the controller:
[HttpPost]
public ActionResult Login(ClsLogin User)
{
string message = "";
if (ModelState.IsValid)
{
message = "Success";
Session["SessionUser"] = User.NombreUsuario;
var sessionuser = new ClsLogin();
if (Session["SessionUser"] != null)
{
sessionuser.SessionValue = Session["SessionUser"].ToString();
}
else
{
sessionuser.SessionValue = "La sesión ha expirado";
}
ViewBag.session = sessionuser;
}
else
{
message = "Uno de los campos es incorrecto";
}
if (Request.IsAjaxRequest())
{
return Json(message, JsonRequestBehavior.AllowGet);
}
else
{
return RedirectToAction("Index", "Home");
}
}
And finally the main view _Layout which is where the Viewbag doesn't work:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width">
<title>ASP.NET Proyect</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery-2.2.1.min.js"></script>
<link href="~/Content/css/_Layout.css" rel="stylesheet" />
<link href="~/Content/css/Styles.css" rel="stylesheet" />
</head>
<body>
<!--Encabezado-->
<header>
<h2 class="padding">Bienvenido</h2>
@ViewBag.session
</header>
<!--Menu-->
<div class="menu-content">
@Html.Partial("_Menu")
</div>
<!--Contenido-->
<div class="body-content">
@RenderBody()
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
I also tried like this @Html.TextBox("mensaje", (string)ViewBag.session)
and it didn't work. Any idea what I'm doing wrong?
The problem is that the data is
ViewBag
only available during the same request. What I see happening is that you fill the value in the actionLogin
and then redirect to the actionIndex
, it is in this second request that the data is no longer available.What you can do is keep using
Session
in your view that if is a class that saves the data between different callsor even use the properties of the object
User
if you just need the name