Modifying MVC 3 ViewBag in a partial view does not persist to the _Layout.cshtml

后端 未结 10 1838

I am using MVC 3 with the Razor view engine. I want to set some values in the ViewBag inside a Partial View and want retrieve those values in my _Layout.cshtml. For exampl

相关标签:
10条回答
  • 2020-12-08 14:16

    I've tried the following and it works:

    In the (parent) view...

    @Html.Partial("SomePartial", ViewData, null)
    

    Note: ViewData is passed as the model argument, but you have to specify null for the viewData argument to use the correct overload. You can't use ViewBag because Html.Partial doesn't like dynamics.

    Then , in the partial view...

    @model ViewDataDictionary
    @{
        Model["Title"] = "About us from the partial view";
    }
    

    Of course, if you need to use the model argument for a real model, you'll have to be more creative.

    0 讨论(0)
  • 2020-12-08 14:17

    If anyone is still looking for a solution to this it appears that you can do it with TempData:

    TempData["x"] = x;
    

    TempData is persisted until it is read so you can just read it in your _Layout. You just have to be careful that you read everything so that it is cleared for the next request.

    0 讨论(0)
  • 2020-12-08 14:22

    You can do this trick in your partial view to override the title in your _Layout.cshtml:

    @{
        ViewBag.Title = "About Us From The Partial View";
    }
    
    ......
    
    <script type="text/javascript">
        document.title = "@ViewBag.Title";
    </script>
    
    0 讨论(0)
  • 2020-12-08 14:22

    I encountered the same problem when I use mvc3, and I found that

    this.ViewBag.ViewBag.PropertyName 
    

    works in your custom control.

    0 讨论(0)
提交回复
热议问题