Search code examples
c#viewasp.net-mvc-5controllers

Getting viewbag dynamic property's value as null


I am storing a value in dynamic property called login in my Login action method in my controller and I am accessing the value of the viewbag in Index view. I am gettng the value as null. Why is this so.?

Following is my code which is in controllers Login action method.

ViewBag.Login = "false";
return RedirectToAction("Index");

here is my code which I am using in the Index view(cshtml).

@if (@ViewBag.Login != "")

Here in view I am getting @ViewBag.Login's value as null. Even if i remove the @ symbol like this

ViewBag.Login  Still I get value as null. 

Please help. ViewBag should persist value within view's and action methods which are bind to same controller.


Solution

  • ViewBag does not persist across http requests.

    You could do

    public ActionResult Login()
    {
       /* Pass `Login` by QueryString */
       return RedirectToAction("Index", new { Login = false });
    }
    
    public ActionResult Index(bool Login) 
    {
       /* Read from QueryString, and pass the value to `ViewBag` */
       ViewBag.Login = Login;
       return View();
    }