Saturday, May 18, 2019

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 name="_content"/>

When we refer to a partial view in other views, we need not specify the path of the partial view file, Asp.Net core searches for the file in the project and automatically embeds the content in the main view. First it searches the current view folder and its parent view folder if any. If the view is not found under the current view or any of its parent view folders it searched for the view in the /Shared folder. Any partial view which is to be used globally in the application should be placed under the /Shared folder.

Let us create a simple partial view _content.cshtml which will just display a single line from the partial view.

Content from the Partial View

Now in the main view, we will embed the partial view as follows.

<p>Content from Main View</p>
<partial name="_content"/>

Build and run the project the output will be as follows.



Search Flipkart Products:
Flipkart.com

No comments: