What is ViewBag.Title
in ASP.NET MVC 4?
I have that View file:
@model IEnumerable<MvcMusicStore.Models.Genre>
@{
ViewBag.Title = "Store";
}
<h2>Index</h2>
and I do not know what changing ViewBag.Title
may accomplish.
What is ViewBag.Title
in ASP.NET MVC 4?
I have that View file:
@model IEnumerable<MvcMusicStore.Models.Genre>
@{
ViewBag.Title = "Store";
}
<h2>Index</h2>
and I do not know what changing ViewBag.Title
may accomplish.
From the ASP.NET site:
The
ViewBag.Title
property is simply a string object. In this case it's being used in the view to actually define theTitle
property. If you were to look in your_Layout.cshtml
file you would likely see something like:Remember when the property was defined in the view? When the page is finally rendered, that property ends up in the HTML markup looking like:
Which sets the browser title.
ViewBag
is a dynamic object so you can define any property on it. In this case@ViewBag.Title
is assigned a string. In the_Layout.cshtml
page you will see this line of code:Any view which is using the
_Layout.cshtml
as the layout will have a line of code similar to below:If you did that, this is eventually what you will accomplish (see the red circle) showing the title of the page in the browser:
In one of your comments you ask:
In other words you are asking if you can put a complex object in
Title
property? Yes, you can do this but keep in mind to change the code in the_Layout.cshtml
file, otherwise it will just callToString()
on your complex object and print the result in the browser title. But why would you do this? I do not suggest it. But yes you can put anything in it because it is dynamic but then you have to use it properly. You can even create other properties like this:However, passing a model is much better because it gives you compiler support and you will also get intellisence.