.net core mvc startup sequence and the main member 4-MVC

MVC earlier chapters have already started the process of explaining to do as well as source code, chapter officially MVC, mvc full name is model view controller, the presentation layer is subdivided into three layers, the official website of Image Caption:

 

The default creates a .net core web project, the Startup type the code below into this

 public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
          
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment environment)
        {
            if (environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseMvcWithDefaultRoute();
        }
    }

 We .net core mvc is based on a model agreement, such as: the controller is on the Controllers folder (of course, this is not required), the view on the pages or folders moderate views, first of all we talk about the Controller of the agreement, regardless exception of the first case, we have to define a Controller to Microsoft.AspNetCore.Mvc.Controller first to inherit the class and requires one of the following conditions which:

1, the class name suffixes that end in Controller

     For example: Create a Home class, its signature should look like this: public class the HomeController: the Controller

2, with a base class to inherit Controller name suffix,

    For example: you have created a BaseController base class, and now need to create the Home category, then his signature can be so: public class Home: BaseController

3, this class with [the Controller] tab

     For example: Create a Home class, its signature should look like this:

      [Controller]

      public class Home : Controller

In the method of the Controller class written inside, we called Action, such as the following, which creates a Action Index, the return value type is a realization example IActionResult interface, here is the return of View

  

 public class HomeController: Controller
    {
        
        public IActionResult Index()
        {
            return View();
        }
       
    }

Here to talk about the View () method in the end what did this thing and let us go to the source code can see the final View is the creation of a ViewResult this class that they inherit to ActionResult and implement a IActionResult interfaces, one of the most the main ExecuteResultAsync way is to return to the front of our data, ViewResult this class we have two regular, ViewName and ViewData, representing the views and needs of the data name of view, if the view name does not pass then the name of the controller is agreed to Action accurate, otherwise prevail name has been passed, if it can be passed in ViewData Model property in the view of inside access to incoming data, and converted to strongly typed, with regard to the above example, we created in the views folder a Home Index.cshtml view files and folders, and creates two entities Models folder, one of the ViewModel general, the code is as follows:

 public class ViewModel<T> where T : class
    {
        public string Title { get; set; }
        public IEnumerable<T> Data { get; set; }
    }

  Another specific Action is required to view data entities, the name of IndexModel, specific code as follows:

public class IndexModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

 In addition, we write a data acquisition service Index, entitled HomeService, and together with the front services.AddScoped <HomeService> () method in ConfigureServices Startup class;

First regardless of whether the design specifications, done so after that we can inject instance HomeService of the other entity, we HomeService code may look like this:

 public class HomeService
    {
        private  IEnumerable<IndexModel> _sourceData = new List<IndexModel>
        {
            new IndexModel { Id = 1, Description = "my is code1", Name = "test1" },
             new IndexModel { Id = 2, Description = "my is code2", Name = "test2" },
              new IndexModel { Id = 3, Description = "my is code3", Name = "test3" },
               new IndexModel { Id = 4, Description = "my is code4", Name = "test4" },
                new IndexModel { Id = 5, Description = "my is code5", Name = "test5" },
        };
        public ViewModel<IndexModel> GetData(int id)
        {
            return new ViewModel<IndexModel>
            {
                Title = "Index",
                Data = id > 0 ? _sourceData.Where(x => x.Id == id) : _sourceData
            };
        }
    }

 This time the HomeController code into this

 

 public class HomeController: Controller
    {
        private readonly HomeService _service;

        public HomeController(HomeService service)
        {
            _service = service;
        }

        public IActionResult Index()
        {
            var data = _service.GetData();
            return View(data);
        }
       
    }

 Then go to view files, view the code as follows:

@model ViewModel<IndexModel>;
@{
    ViewData["Title"] = Model.Title;
}
<ul>
    @foreach (var item in Model.Data)
    {
        <li>
            <span>名称:@item.Name</span>
            <span>说明:@item.Description</span>
            <a asp-action="details" asp-route-id="@item.Id">详细</a>
        </li>
    }
</ul>

 In view of the code which has a noteworthy

<a asp-action="details" asp-route-id="@item.Id"> </a> details 
of this improvement is .net core portion, it is called TagHelpers, which is parsed by .net core, eventually become normal src attribute or other html attributes, the benefits of doing so is closer to programmatically html itself,
here we have noticed defined asp-action = "details" to indicate that the controller method in the current view details , eventually resulting url path is / home / details id = {id },?
to be able to run properly, we need to create a details method, as follows:
   public IActionResult Details(int id)
        {
            var data = _service.GetData(id);
 data.Title = "Details"; return View(data); }

  In view file details of creation, the code is as follows:

@model  ViewModel<IndexModel>
@{
    ViewData["Title"] = Model.Title;
    var data = Model.Data.FirstOrDefault();
}

    <p>@data.Name,@data.Description,@data.Id</p>

  Then we run the program, you will see the following interface:

Click on "details" will appear the following screen:

Well, mvc general situation described here, the back will explain in detail some of the rules Views in this folder as well, are interested can go to the official website to see https://docs.microsoft.com/zh-cn/aspnet /core/razor-pages/?view=aspnetcore-2.2&tabs=visual-studio

Guess you like

Origin www.cnblogs.com/lvshunbin/p/11113487.html
Recommended