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";
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With