Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set page title from a partial page in MVC


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";
like image 780
Cagatay Avatar asked Nov 04 '15 11:11

Cagatay


1 Answers

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>
like image 84
Joseph Woodward Avatar answered Sep 30 '22 18:09

Joseph Woodward