简体   繁体   中英

How ASP.NET MVC _layout variables work?

When I create a new ASP.NET 4.5 web application MVC in Visual Studio, it starts with a introduction template.

The relavant parts are:

Views/Home/About.cshtml

@{
    ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
...

Views/Shared/_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title - My ASP.NET Application</title>
...
    @RenderBody()
...

Views/_ViewStart.cshtml

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

If I understand right, and assuming the About page is opened in the browser:

  • The _ViewStart.cshtml is called first, and it says there is a layout _Layout.cshtml to be called.

  • It renders the _Layout.cshtml , until the call @RenderBody() is reached, on that point he will render the About.cshtml . When that ends, he will render the rest of the _Layout.cshtml .

But here is my doubt, if the _Layout.cshtml starts first, how does it print on the <title> the variable @ViewBag.Title , which is assigned only in About.cshtml ?

When you hit a URL an Action is called on a controller . The view is a result of this, so you don't call views directly (my guess is your coming from a webforms background where you call an aspx page, MVC uses a different model that doesn't rely on physical files). The action then specifies which view to render (and passes it the model). This view then specifies a layout to use when rendering the view.

So the control mechanism is inverted compared to what your used to.

URL (via routing) specifies a controller and an action -> the action says render me using this view -> the view then says render me using this layout. So the hierachy is:

  • Controller
  • Action
  • View
  • Layout

So to answer your specific questions:

But here is my doubt, if the _Layout.cshtml starts first, how does it print on the <title> the variable @ViewBag.Title , which is assigned only in About.cshtml?

The layout isn't called first, the view specifies a layout that should be used to render itself.

It doesn't. The View is rendered before the layout.

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