What is ViewBag.Title in Razor?

2019-03-17 09:20发布

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.

2条回答
Juvenile、少年°
2楼-- · 2019-03-17 09:29

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.

查看更多
女痞
3楼-- · 2019-03-17 09:41

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:

enter image description here


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.

查看更多
登录 后发表回答