6


I am trying to get page title from a partial page but i coundn't do it in MVC. Do you have any idea?

in a child.cshtml:

@{ViewBag.Title="this is child"}  > this is not working in a child

I tried to get information ViewData like:

in a viewpage.cshtml

ViewBag.Title = ViewData["pagetitle"];

in a child.cshtml:

ViewData["pagetitle"] = "this is child";
Cagatay
  • 333
  • 1
  • 3
  • 13
  • 1
    Duplicate of [http://stackoverflow.com/questions/11509996/set-a-page-title-from-a-partialview](http://stackoverflow.com/questions/11509996/set-a-page-title-from-a-partialview) – user1672994 Nov 04 '15 at 11:34
  • Are you using `_Layout.cshtml`? If so, how are you displaying the `@ViewBag.Title`? – markpsmith Nov 04 '15 at 11:37
  • i am using _layout.cshtml and i don't have a problem with changing page title in a view. My partial is part of view. _Layout > _viewpage > _partialpage and your link is not working for me :) – Cagatay Nov 04 '15 at 11:43

2 Answers2

9

Unfortunately you cannot do it within a partial view.

The reason for this is by the time your partial view gets parsed by the view parser, the main layout (which contains the <title></title> tags) has already been written to your applications response stream ready to be flushed to the browser.

If you REALLY need to then I suppose you could parse the current response stream and use regular expression to match and replace the page title, but I wouldn't suggest this as it's pretty inefficient.

As others have said, your better option (albeit not ideal - one reason being the importance a title tag is to search engines) is set the title using Javascript.

This can be achieved like so:

<script type="text/javascript">
document.title = '@ViewBag.Title';
</script>
Joseph Woodward
  • 9,191
  • 5
  • 44
  • 63
  • i understand but it should be a way to move data from partial page to view page right? – Cagatay Nov 05 '15 at 11:01
  • No, from all of the investigating I've done in the pass it's not possible. The parent view can pass data to a partial view but not the other way around. – Joseph Woodward Nov 05 '15 at 11:03
  • @Cagatay You can accomplish this by creating a ViewModel for your layout that gets created with the partial view's ViewModel. The layout's VM could be placed in the `ViewBag` or `ViewData`, but because you're building it during the request for the partial, you can set a Title property on it to whatever you want. I've done this by creating a layout VM with a generic `T` property for the partial's VM type and I build the layout VM in a base controller so the partial's action doesn't have to worry about it. But not from directly in the view. – xr280xr Jun 16 '20 at 00:59
4

Setting title like @{ ViewBag.Title = "..."; } in a child view will not work if you have title in your layout. Setting title is not a responsibility of PartalView.

Instead you can use javascript, like this:

document.title = "new title";
Vnuuk
  • 6,177
  • 12
  • 40
  • 53