Showing posts with label Partial Views. Show all posts
Showing posts with label Partial Views. Show all posts

Saturday, May 18, 2019

Partial view with Model example in Asp.Net Core

In the previous post we saw a simple Partial View example, where a string from the partial view is displayed in the main view page. In this post we will improve this example to take a Model object and display the properties in the Model object.

When invoking a partial view from a main view, we can also pass a Model object to the partial view as follows. The properties in the passed model can be used in the HTML markup of the partial view.

Partial view example in Asp.Net Core

Partial views are views whose content gets embedded in other View pages, partial views are added to other views using the <partial> element or using @Html.Partial helper tags. In this post we shall see a simple example of how to create a partial view and embed it in the main view page.

Partial views are usually named with a _ character in from of the view name to differentiate between partial views and other views. The following line shows how a partial view is referenced inside other views.

Partial views in Asp.Net Core MVC Views

A Partial View is another view page with .cshtml extension, Partial Views are used to modularize larger view pages and also to re-use common functionality across different views in the application.

Partial views improve maintainability by breaking down a large view page into modular views and embedding the partial views in the main view template. By doing this the markup code in the main view page reduces there by improving readability and maintainability.

Partial views also help reduce duplication of code in larger applications, if we have a common functionality / display content which is to be repeated in many places the a large application, then we can place the repeating content in a partial view and just embed the partial view wherever required. This reduces duplication of same logic in many places. Also improves maintainability since any change to the common logic needs to be done in only one place, in the partial view.

The syntax for including partial views varies by the version of Asp.Net Core used, in Asp.Net Core 2.1 we use the partial tag to include partial views as follows.