开发者

Page title problem when setting ViewBag variable from razor section in asp.net mvc

Consider fallowing declaration in view

@section sideaction
{
  ...
  ViewBag.Title=Model.Title;
  ...
}

And in main layout i have this

<head>
    <title> @ViewBag.Title</title>
....
...
</head>
..
...
<body>
..
 @RenderSection("sideaction",required:false)
..
</body>

I am not getting 开发者_Python百科title from view, i know that view will be processed before layout but i recognized that head section is processed before render section which is causing this problem. One more thing , ViewBag.Title=Model.Title is just an example , the real Model is IEnumrable object and i am iterating and finding proper title. I can iterate in controller to find title but there is already iteration in view. For big collections one iteration is more efficient. Any ideas?


You cannot set a ViewBag value in a section.

Use this:

@{
    ViewBag.Title = Model.Title;
}

directly in the view to set a title.


Even it doesn't work, notice that the code has to be like this:

@section sideaction
{
    @{
       ViewBag.Title = Model.Title;
    }
}

But as other people mentioned earlier, you can't do it this way inside a section. You should put it directly inside your view:

@{
    ViewBag.Title = Model.Title;
}

By the way, if you persist to change title of a page from inside a section, use javaScript/jQuery, e.g:

@section sideaction
{
    <script type="text/javascript">
        $(function () {
            document.title = '@Model.Title';
        });
    </script>
}

Note: pay attention that it has to be '@Model.Title' (inside quotes).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜