Why can't _ViewStart.cshtml access the ViewBag object?

前端 未结 6 1806
孤街浪徒
孤街浪徒 2020-12-30 19:12

I have the default _ViewStart.cshtml in my /Views folder. I\'d like to be able to access my ViewBag object so I can set the default title for all my views.

However,

6条回答
  •  臣服心动
    2020-12-30 19:43

    In short... Use the controller's view bag.

    ViewContext.Controller.ViewBag.MyVar = "myVal";
    

    and

    @ViewContext.Controller.ViewBag.MyVar
    

    ===============================================================

    There is good information here: http://forums.asp.net/post/4254825.aspx

    ===============================================================

    Generally, ViewData["StoreName"] is same as ViewBag.StoreName

    Also, Controller.ViewData["StoreName"] = Controller.StoreName = ViewContext.Controller.ViewBag.StoreName =ViewContext.Controller.ViewData["StoreName"]

    But every view and partial view gets its own instance of viewdata.

    http://jeffreypalermo.com/blog/viewdata-mechanics-and-segmentation-excerpt-from-asp.net-mvc-in-action/

    ===============================================================

    There is a another solution here: https://stackoverflow.com/a/4834382/291753

    ===============================================================

提交回复
热议问题