📅  最后修改于: 2023-12-03 15:35:35.742000             🧑  作者: Mango
ViewBag is a dynamic property that allows you to share data between the controller and the view in ASP.NET MVC. It is a part of the ViewBag object, which is a dynamic object that can be used to store and retrieve data across different parts of the application.
ViewBag.Title is a property of the ViewBag object that is specifically used to set the title of a view. This is commonly done in the controller action method, where the title is set based on the specific content that is being displayed. For example, if the view is displaying a list of products, the title might be "Products".
Using ViewBag.Title is a simple process. First, you need to set the Title property in the controller method that corresponds to the view (this is typically done in the method that returns the view):
public ActionResult Index()
{
ViewBag.Title = "Products";
return View();
}
Then, in the view, you can access the Title property and use it to set the title of the page:
@{
ViewBag.Title = "Products";
}
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<h1>@ViewBag.Title</h1>
<!-- rest of the view code here -->
</body>
</html>
Using ViewBag.Title to set the title of a view has several benefits:
Overall, ViewBag.Title is a simple but effective way to set the title of a view in ASP.NET MVC. By using this property, you can keep your code organized, maintainable, and user-friendly.