Reputation: 11926
In my controller say ControllerFirst
I am setting a ViewBag
property by the below line.
ViewBag.PreviousPage="ThisIsComingFromControllerFirst";
return RedirectToAction("ControllerSecond", "Home");
Now from here:
public ActionResult ControllerSecond()
{
return View();
}
I am trying to use Viewbag
in the ControllerSecond
by the following
View: ControllerSecond.cshtml
@if(ViewBag.PreviouPage == "SomeValue")
{
//do this
}
But ViewBag.PreviousPage
value is null.
Please let me know why its null, what could I do to get the value in my view from the ControllerFirst
.
I have done this one using Session
, but We don't want to sessions..
Any other options?
Upvotes: 1
Views: 5368
Reputation: 93464
To answer your first question, ViewBag is a more convenient form of ViewData that uses dynamic objects rather than generic ones. As with ViewData, ViewBag only exists for the life of a single request, thus it is only available between the ActionMethod and it's view. It is not available between different ActionMethods.
Think of it like an intercom system in a home. You can send messages to other parts of the home, but you can't send a message to a neighbors home.
The only other options you have are:
Upvotes: 3
Reputation: 56024
ViewBag
(and ViewData
) are objects for accessing extra data (i.e., outside the data model), between the controller and view.
If your data have to persist between two subsequent requests you can use TempData
.
However, TempData
is by default stored in the session.
So, if you don't want to use sessions, you could use cookies and somehow duplicate a bit of what session does for you, as MikeSW suggested.
When to use ViewBag, ViewData, or TempData in ASP.NET MVC 3 applications
Upvotes: 1
Reputation: 16378
You can use a cookie and somehow duplicate a bit of what session does for you.
Upvotes: 0