What is ViewBag.Title in Razor?

廉价感情. 提交于 2019-12-20 16:28:33

问题


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.


回答1:


From the ASP.NET site:

ViewBag is a dynamic object, which means you can put whatever you want in to it; the ViewBag object has no defined properties until you put something inside it.

The ViewBag.Title property is simply a string object. In this case it's being used in the view to actually define the Title property. If you were to look in your _Layout.cshtml file you would likely see something like:

<title>@ViewBag.Title</title>

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:

<title>Store</title>

Which sets the browser title.




回答2:


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:

<title>@ViewBag.Title</title>

Any view which is using the _Layout.cshtml as the layout will have a line of code similar to below:

@{
    // This is setting the property to Hahaha
    ViewBag.Title = "Hahaha"; 
}

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:

Does whatever I want means also to put an complex object in it? I know that this suppose to be done by passing object to the model, but is this doable?

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 call ToString() 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:

ViewBag.SomeOtherProperty = new MyClass() {...};

However, passing a model is much better because it gives you compiler support and you will also get intellisence.



来源:https://stackoverflow.com/questions/24354004/what-is-viewbag-title-in-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!