Introduction to ASP. NET Core part 2 Views and asp. netcore
Problem
In ASP. NET Core 2.0, how does one use partial views to reuse the public part of a page?
Answer
Create an empty project and add the MVC service and middleware to Startup:
public void ConfigureServices(IServiceCollection services){ services.AddMvc();} public void Configure(IApplicationBuilder app, IHostingEnvironment env){ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });}
Add two models:
public class EmployeeViewModel{ public int Id { get; set; } public string Firstname { get; set; } public string Surname { get; set; } public AddressViewModel Address { get; set; }} public class AddressViewModel{ public string Line1 { get; set; } public string Line2 { get; set; } public string Line3 { get; set; }}
Add a controller, return ViewResult, and pass in the model instance:
public class HomeController : Controller{ public IActionResult Index() { var model = new EmployeeViewModel { Id = 1, Firstname = "James", Surname = "Bond", Address = new AddressViewModel { Line1 = "Secret Location", Line2 = "London", Line3 = "UK" } }; return View(model); }}
Add view page Index. cshtml:
@using PartialView.Models;@model EmployeeViewModel <div style="border: 1px solid black; margin: 5px">
Add some view_address. cshtml:
@using PartialView.Models@model AddressViewModel <div style="border: 1px dashed red; margin: 5px">
Now, the directory structure in the solution is as follows:
Run:
Discussion
Some views are special views rendered to other views. This is useful for reusing some of the views or separating a large view into some small components.
Some views can be created like normal views, and ViewResult can be returned through the Controller method. The key difference is that some views do not run _ ViewStart. cshtml before rendering, and it is usually rendered inside other views.
Inside a view, some views are rendered using the @ Html. Partial () method, and the names of some views and an optional model instance are input. Some view names can be absolute or relative paths. The view engine searches for corresponding views in the current directory and Shared directory.
Some views can obtain a copy of the ViewData of the parent view. You can also input a model to it, which is usually part of the parent view model.
Note: ASP. NET Core also provides a more flexible solution to reuse or separate views. This solution not only runs code, but also does not need to depend on the parent view. It is a view component, which will be introduced in the next section.
Source code download
Original article: https://tahirnaushad.com/2017/08/24/asp-net-core-2-0-mvc-partial-views/
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.