开发者

MVC3 ViewBag not working

I开发者_运维技巧n 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


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.


Instead of writing

return RedirectToAction("Index");

simply write

return View();

RedirectToAction("Index") , clears ViewBag


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜