Hari Gillala
Hari Gillala

Reputation: 11926

ViewBag Usage-ASP.NET MVC3

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

Answers (4)

Erik Funkenbusch
Erik Funkenbusch

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:

  • Use Session
  • Use TempData (which also uses session)
  • Use a Cookie
  • Use a querystring parameter
  • Use an intermediate table in your database
  • Post to ActionMethod

Upvotes: 3

Paolo Moretti
Paolo Moretti

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

MikeSW
MikeSW

Reputation: 16378

You can use a cookie and somehow duplicate a bit of what session does for you.

Upvotes: 0

wnascimento
wnascimento

Reputation: 1959

Use TempData instead of ViewBag

Upvotes: 0

Related Questions