简体   繁体   中英

What is the exact meaning of this ViewBag setting into a .NET Razor page?

I am very new in .NET (I came from Java and Spring framework) and I have the following doubt about Razor pages.

I have a very simple page like this:

@model Vidly.Models.Customer

@{
    ViewBag.Title = Model.Name;
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>@Model.Name</h2>

the first line declare the model object used by this page having type Vidly.Models.Customer (it contains the data used into the view), infact I access and show the value of the Vidly.Models.Customer.Name property by:

<h2>@Model.Name</h2>

My doubt is related to this section of the previous code:

@{
    ViewBag.Title = Model.Name;
    Layout = "~/Views/Shared/_Layout.cshtml";
}

What is it exactly doing?

I think that it is declaring some kind of object containing 2 properties that represent something like the settings of this view page (correct me if I am doing wrong assertion).

By this line it is declaring what is the page layout:

Layout = "~/Views/Shared/_Layout.cshtml";

But what exactly means this line:

ViewBag.Title = Model.Name;

What is the ViewBag ? and what means this setting? Model.Name should contain the value of the Name property inside the passed model object. What is exactly doing?

In general it is used for passing small amounts of data among controllers and views.

In the above example is it most likely setting the title of the page which is usually in the _Layout.cshtml

<title>My Page - @ViewBag.Title</title> 

In ASP.NET MVC there are three ways - ViewData, ViewBag and TempData to pass data from controller to view.

What is the ViewBag?

  • ViewBag can be used to transfer data from the controller to the view, mostly temporary data.
  • The ViewBag's exist only with the http request. It will be destroyed on redirection.
  • ViewBag is a property of ControllerBase class.

What exactly means this line:

ViewBag.Title = Model.Name;

ViewBag can be more convenient to work with, since it doesn't require casting. You are setting the title using ViewBag. Since the ViewBag derives from DynamicViewData, this means that can allows the creation of dynamic properties using dot notation @ViewBag.SomeKey = <value or object> .

Note: ViewBag isn't available in Razor Pages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM