ASP.NET Core MVC views

The responsibility of a view is to transform a model into HTML or other formats. There are multiple view engines that can be used to do this. The default view engine for ASP.NET MVC 3 and later is called Razor, and it uses the @ symbol to indicate server-side code execution.

Rendering the Home controller's views

Expand the Views folder, and then expand the Home folder. Note the three files with the .cshtml file extension.

Note

The .cshtml file extension means this is a file that mixes C# and HTML.

When the View() method is called in a controller's action method, ASP.NET Core MVC looks in the Views folder for a subfolder with the same name as the current controller, that is, Home. It then looks for a file with the same name as the current action, that is, Index, About, or Contact.

In the Index.cshtml file, note the block of C# code wrapped in @{ }. This will execute first and can be used to store data that needs to be passed into a shared layout file:

    @{ 
      ViewData["Title"] = "Home Page"; 
    } 

Note the static HTML content in several <div> elements that uses Bootstrap for styling.

Tip

Good Practice

As well as defining your own styles, base your styles on a common library, such as Bootstrap, that implements responsive design. To learn more about CSS3 and responsive design, read the book Responsive Web Design with HTML5 and CSS3 - Second Edition by Packt Publishing at https://www.packtpub.com/web-development/responsive-web-design-html5-and-css3-second-edition.

Sharing layouts between views

There is a file named _ViewStart.cshtml that gets executed by the View() method. It is used to set defaults that apply to all views.

For example, it sets the Layout property of all views to a shared layout file:

    @{ 
      Layout = "_Layout"; 
    } 

In the Shared folder, open the _Layout.cshtml file. Note that the title is being read from the ViewData dictionary that was set earlier in the Index.cshtml view.

Modify the title to have the suffix, My First ASP.NET Core App, as shown in the following markup:

    <title>@ViewData["Title"] - My First ASP.NET Core App</title> 

Note the rendering of common styles to support Bootstrap and the two sections. During development, the fully commented and nicely formatted versions of CSS files will be used. For staging and release, the minified versions will be used:

    <environment names="Development"> 
      <link rel="stylesheet"
    href="~/lib/bootstrap/dist/css/bootstrap.css" /> 
      <link rel="stylesheet" href="~/css/site.css" /> 
    </environment> 
    <environment names="Staging,Production"> 
      <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/ 
                 bootstrap/3.3.5/css/bootstrap.min.css"  
        asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"  
        asp-fallback-test-class="sr-only"  
        asp-fallback-test-property="position"  
        asp-fallback-test-value="absolute" /> 
      <link rel="stylesheet"  
            href="~/css/site.min.css"  
            asp-append-version="true" /> 
    </environment> 

Note

~ means the wwwroot folder.

Note the rendering of hyperlinks to allow users to click between pages using the navigation bar at the top of every page. The <a> elements use "tag helper" attributes to specify the controller name and action name that will execute when the link is clicked:

    <div class="navbar-collapse collapse"> 
      <ul class="nav navbar-nav"> 
        <li><a asp-controller="Home" asp-action="Index">Home</a></li> 
        <li><a asp-controller="Home" asp-action="About">About</a></li> 
        <li><a asp-controller="Home"  
               asp-action="Contact">Contact</a></li> 
      </ul> 
    </div> 

Note the rendering of the body:

    @RenderBody() 

Note the rendering of script blocks at the bottom of the page so that it doesn't slow down the display of the page:

    <environment names="Development"> 
      <script src="~/lib/jquery/dist/jquery.js"></script> 
      <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script> 
      <script src="~/js/site.js" asp-append-version="true"></script> 
    </environment> 
    <environment names="Staging,Production"> 
      <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-
    2.1.4.min.js" asp-fallback-src="~/lib/jquery/dist/jquery.min.js" 
                  asp-fallback-test="window.jQuery"> 
      </script> 
      <script
    src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.5/bootstrap.min
    .js" asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js" 
    asp-fallback-test="window.jQuery && window.jQuery.fn &&
    window.jQuery.fn.modal"> 
      </script> 
      <script src="~/js/site.min.js" asp-append-version="true"> 
      </script> 
    </environment> 

You can add your own script blocks into an optional defined section named scripts:

    @RenderSection("scripts", required: false) 

Defining custom styles

In the wwwrootcss folder, open the site.css file.

Add a new style that will apply to an element with the newspaper ID like this:

    #newspaper { 
      column-count: 3; 
    } 

Note

In Visual Studio Code, you will need to add the style to site.min.css too. Usually you would have a build step to minify your site.css into a site.min.css, but for now, just do it manually.

Defining a typed view

To improve the IntelliSense when writing a view, you can define the type the view can expect using a @model directive at the top.

Back in the Index.cshtml view, enter the following code as the first line of the file:

    @model Packt.CS7.HomeIndexViewModel 

Now, whenever we enter @Model in this view, the IntelliSense will know the correct type and will provide IntelliSense.

Note

To declare the type for the model, use @model (with lowercase m).

To read from the model, use @Model (with uppercase M).

In Index.cshtml, delete all the <div> elements and replace them with this markup:

    <div class="row"> 
      <div class="col-md-12"> 
        <h1>Northwind</h1> 
        <p class="lead">We have had @Model.VisitorCount
           visitors this month.
        </p> 
        <h2>Products</h2> 
        <div id="newspaper"> 
          <ul> 
          @foreach (var item in @Model.Products) 
          { 
            <li><a asp-controller="Home"  
                   asp-action="ProductDetail"  
                   asp-route-id="@item.ProductID"> 
                @item.ProductName costs  
                @item.UnitPrice.Value.ToString("C") 
            </a></li> 
          } 
          </ul> 
        </div> 
      </div> 
    </div> 

Note how easy it is to mix static HTML elements such as <ul> and <li> with C# code to output the list of product names.

Note the <div> element with the id attribute of newspaper. This will use the custom style that we defined earlier, so all the content in that element will display in three columns.

In Visual Studio 2017, press Ctrl + F5.

In Visual Studio Code, enter the command dotnet run, and then run Chrome and navigate to http://localhost:5000/.

The home page will look as shown in the following screenshot:

Defining a typed view

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.36.38