Can't access ViewBag in a partial view in ASP.NET MVC3

后端 未结 8 1390
无人共我
无人共我 2020-12-08 06:32

I have a controller calling a view. In the view there is a PartialView called be @Html.Partial(\"ViewName\", model). This works fine.

But i

相关标签:
8条回答
  • 2020-12-08 07:02

    That should work without any problems. In my HomeController Index action I add a message to the ViewBag:

    ViewBag.Message = "Welcome to ASP.NET MVC!";
    

    On the Index View I add the partial view:

    @Html.Partial("ViewName")
    

    And on the partial view I render the message:

    @ViewBag.Message
    

    From the comments below: there seems to be a problem when you pass a model to the partial view. Then you can refer to the original ViewBag with

    @ViewContext.Controller.ViewBag.Message
    
    0 讨论(0)
  • 2020-12-08 07:02

    In my case @ViewContext.Controller.ViewBag.Message didn't work as well. I have a partial view that is referenced from different controllers with different models, inherited from a base model class. In this case the Controller.ViewBag comes as null.

    My solution is:

    @{
    var dummy = ViewContext.Controller.ViewData.TryGetValue("CommonRules", out object rules);
    }
    ...
    @Html.Raw(rules)
    
    0 讨论(0)
提交回复
热议问题