Melissa
Melissa

Reputation: 1

MVC3 ViewBag not working

In my action controller I am setting the following:

    ViewBag.headerinfo = "ddddddddddd";
    ViewBag.Info = "abc";

In my _Layout view I have:

<div id="header_infobox"> 
    @ViewBag.Info  bbbbb
    @ViewBag.headerinfo
</div>

When it comes to dispaly all I see is bbbbb. I can't understand why ViewBag doesn't work. I hope someone can give me advice.

Thanks,

Melissa

Upvotes: 0

Views: 4364

Answers (3)

Prateek Gupta
Prateek Gupta

Reputation: 908

Instead of writing

return RedirectToAction("Index");

simply write

return View();

RedirectToAction("Index") , clears ViewBag

Upvotes: 2

Crims0nTider
Crims0nTider

Reputation: 51

I had the same problem. For me, it was because I was returning RedirectToAction instead of just returning the View. When you RedirectToAction, it apparently clears out the ViewBag.

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

Works great (newly created ASP.NET MVC 3 application using the default Visual Studio template):

Controller (~/Controllers/HomeController.cs):

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.headerinfo = "ddddddddddd";
        ViewBag.Info = "abc";
        return View();
    }
}

View (~/Views/Home/Index.cshtml):

<div id="header_infobox"> 
    @ViewBag.Info  bbbbb
    @ViewBag.headerinfo
</div>

Resulting HTML (as seen in browser view source):

<div id="header_infobox"> 
    abc  bbbbb
    ddddddddddd
</div>

Upvotes: 1

Related Questions