[Asp.net core series] 3 views and views and controllers

Posted Jun 16, 20206 min read

  1. Introduction

In the previous articles, we have outlined how to create an asp.net core mvc project and how http requests are routed to the corresponding execution unit. In this article, we will introduce the direct relationship between the controller and the view.

1. view

The view here is not a view in the database, but a display technology. In the asp.net core mvc project, the view refers to the file with cshtml extension, usually in the Views folder.

So now we go to the Views directory of the previously created test project MvcWeb. If the friends have not modified it, we can see the following directory structure:

    Home
      Index.cshtml
      Privacy.cshtml
    Shared
      Error.cshtml
      _Layout.cshtml
      _ValidationScriptsPartial.cshtml
    _ViewImports.cshtml
    _ViewStart.cshtml

In the root directory of Views, there are two files:_ViewImports.cshtml and _ViewStart.cshtml(note that there is a leading underscore).

1.1 Referencing namespaces in views

We know that in the cshtml file, although the server code is greatly reduced, sometimes some C# code cannot be avoided. Then there will be a problem. Many classes have their own namespaces. If we need to access these classes and methods in one or a few or some views, it is a little unrealistic to write references for one view and one view. Because it is too cumbersome.

So asp.net core mvc is set to add a reference in the file named _ViewImports.cshtml, it will take effect in all views under Views. So, let's take a look at what is in this file:

@using MvcWeb
@using MvcWeb.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

As you can see, all the contents of the project's namespace and the Modes namespace under the project are referenced here. Because the name of the test project we created earlier is MvcWeb.

The last line is a cshtml tag reference, the first asterisk indicates that all TagHelper implementations of the current project are referenced, and the latter indicates the introduction of TagHelper built into aps.net core mvc.

About TagHelper, this article will not be introduced first.

1.2 ViewsStart

The role of _ViewStart.cshtml can be seen from the name. This file is used to configure some configuration contents when the view starts to load. Let's take a look first, what is inside the default:

@{
    Layout = "_Layout";
}

First, let's make an introduction. The @ symbol is wrapped with a pair of braces, and the C# code is inside. That is to say Layout = "_Layout", the meaning of this line is to set the value of a certain property named Layout to _Layout.

So, what are the properties of Layout?

For asp.net core mvc, a view is also a class, but this class is dynamically generated, not a class written by a programmer, but this class inherits from:

namespace Microsoft.AspNetCore.Mvc.Razor
{
    public abstract class RazorPageBase:IRazorPage
    {
    }
}

Layout happens to be an attribute of this class, indicating whether the view uses a certain layout page. So the above code indicates that the newly created view in Views uses the view named _Layout as the layout page by default.

Of course, this page has more than just this function, and friends can try it for themselves.

1.3 View retrieval

In the previous section, we specified the name of a layout page. The layout page is also a kind of view, but we also only specify the name, but not the path. How did asp.net core discover the view with this name?

asp.net core will search for the corresponding view file in the following order:

  • Views/[ControllerName]/[ViewName].cshtml
  • Views/Shared/[ViewName].cshtml

Therefore, _Layout will also be searched in this order. To avoid unnecessary confusion, we only wrote _Layout.cshtml in the Shared directory. This is also common practice, the file represents a global layout page.

2. The relationship between the controller and the view

In the previous article "[asp.net core series]2 the grudges of controllers and routers", we introduced three methods for creating controllers, and finally recommended the use of names that end with Controller and inherit the wording of the Controller class. I will explain to you again why I recommend this:

  • Ending with Controller, you can clearly tell other people or yourself in the future that this is a controller, not another class
  • Inherit Controller, because the Controller class provides us with the properties and methods used by the controller

Well, these two points for now. Don t look less, but it s important.

2.1 Using views

In the previous introduction, it was mentioned that when we visit a URL, the route will automatically find the corresponding executable code unit for us. However, there is no further introduction. When we find the corresponding executable code unit is the Action, the Action performs a series of processing and will respond to this request. One response is to return a display page, which is View.

So, how to return a View?

Create a controller named ViewDemoController and add a method Index with a return type of IActionResult:

using Microsoft.AspNetCore.Mvc;

namespace MvcWeb.Controllers
{
    public class ViewDemoController:Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

View() means to return a View, the name of this View is Index, under the ViewDemo controller. So, its path should be:

Views/ViewDemo/Index.cshtml

Create the file in the corresponding directory, then write some content in the file, and then start the project(the port of the project has been modified in the first part):

http://localhost:5006

Then visit:

http://localhost:5006/ViewDemo/

image-20200601225734470

It should be a similar page.

IActionResult is an interface that represents the processing result of an Action, which can be understood as a fixed writing here.

2.2 Specifying the view

In the controller, the View method indicates that a view is used for rendering. The default is to use the view with the same name as the method. Of course, since it is the default, there must be times when it is not. Yes, the View method provides several overloaded versions. These overloaded versions have a parameter named viewName, which is used to specify the view name.

So, we can specify which view names:

  • Other views under the same controller folder
  • View under Shared folder

Both of these are view names without carrying a path, and the file extension(cshtml) can be omitted.

Of course, you can also specify view files under other paths, such as:

  • Views/Home/About.cshtml indicates that this view is found from the root directory, this writing method must specify the extension
  • ../Manage/Index represents the Index under the Manage controller directory

2.3 Passing data to the view

Earlier, I introduced how to use a view and how to specify a view name, but the most critical step is how to pass data to the view.

Usually, in the Action method to pass data to the view, only these three are recommended:

  • Use ViewData
  • Use ViewDataAttribute
  • Use ViewBag
  • Use ViewModel

One attribute of the Controller class is ViewData, and its declaration is as follows:

public ViewDataDictionary ViewData {get; set;}

You can see that this is a dictionary property, so the assignment to it is used like this:

public IActionResult Index()
{
    ViewData["Title"]= "ViewDemo";
    return View();
}

ViewBag is also an attribute of the Controller class, and its declaration is as follows:

public dynamic ViewBag {get;}

It can be seen that this is a dynamic class. In fact, the data in ViewBag and ViewData are interlinked. In other words, ViewBag is a package of ViewData. There is no actual difference between the two. Assignment use:

public IActionResult Index()
{
    ViewBag.Name = "Little Li";
    return View();
}

The ViewDataAttribute is not the same as the previous two. This attribute is marked to the attribute of the controller. Asp.net core mvc will fill the value of this attribute into ViewData. The key value is the attribute name:

[ViewData]
public string AttributeTest{get;set;}

Same effect as ViewData["AttributeTest"].

In some overloaded versions of the View method, a parameter called model is required and the type is object. This parameter is a ViewModel. use:

Add a class under MvcWeb/Models:

namespace MvcWeb.Models
{
    public class ViewModelTestModel
    {
        public string Name{get;set;}
        public int Age{get;set;}
    }
}

Back in the Index method just now, create a ViewModelTestModel instance and pass it to the View method:

public IActionResult Index()
{
    ViewData["Title"]= "ViewDemo";
    ViewBag.Name = "Little Li";
    var model = new ViewModelTestModel
    {
        Name = "Test Example",
        Age = 1
    };
    return View(model);
}

2.4 Use in views

In the previous section, we used ViewData and ViewBag and ViewModel to pass three data to the view, so how to get these three data in the view?

<h2>@ViewData["Title"]</h2>
<!--The actual display will be <h2>ViewDemo</h2>-->

Like a dictionary, @ means that an attribute or a C# expression is followed, and the result of the expression is output to the page.

ViewBag access is similar to ViewData, except that ViewBag is a dynamic object. It can be considered that its type has not changed. Continue to use it according to the previous type:

<h4>@ViewBag.Name</h4>

For the use of ViewModel, View has a dynamic Model property. Without special processing, we use @Model on the page to get a dynamic object(if ViewModel is passed). Although it works, it is not very friendly.

At this time, we need to add at the beginning of the view:

@model ViewModelTestModel

At this time, when you use @Model, it will automatically parse into ViewModelTestModel.

The overall Index.cshtml content is as follows:

@model ViewModelTestModel
Hello World!
<h2>@ViewData["Title"]</h2>

<h4>@ViewBag.Name</h4>
@Model.Name + @Model.Age

Then after restarting the service, refresh the page, you will see similar content:

image-20200601235928566

3. Summary

In this article, we introduced some concepts of views and introduced how to use controllers to pass data to views. The next article will explain the advanced role of routing, how to carry data through routing.

For more content, please pay attention to My Blog "Mr. Gao's Cabin"

file