Edu
Edu

Reputation: 2643

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:

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?

Upvotes: 0

Views: 1138

Answers (2)

Liam
Liam

Reputation: 29754

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.

Upvotes: 3

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

Upvotes: -1

Related Questions