Home » ASP.Net Razor Partial Views

ASP.Net Razor Partial Views

by Online Tutorials Library

ASP.NET Razor Partial Views

ASP.NET provides a facility to create reusable components so that, that can be shared in the web application. These sharable components are known as partial views.

A partial view is a view which can be plugged in parent view. This view file has the same extension as other views have .cshtml.

When Should We Use Partial Views?

When having a large view file that contains several logical sections, we can break it into smaller components that further can be rendered as partial view.

Note:- Razor views works on DRY (Don’t Repeat Yourself) concept.

ASP.NET provides following two methods to render partial view.

Method Description Overloaded Methods
Partial(String) It renders the specified partial view as an HTML-encoded string. Partial(String, Object) Partial(String, Object, ViewDataDictionary) Partial(String, ViewDataDictionary)
RenderPartial(String) It renders the specified partial view by using the specified HTML helper. RenderPartial(String, Object) RenderPartial(String, Object, ViewDataDictionary) RenderPartial(String, ViewDataDictionary)

Both the methods are used to render partial view, except that the RenderPartial() has void return type. RenderPartial() has better performance than Partial().


Creating a Partial View

To create a partial view, right click on the Views folder or subfolder of it then add view as we did in the following screenshot.

ASP Razor partial views 1

After adding, it creates a file PartialViewDemo.cshtml that contains no productive code.

We have a view that contains some HTML source. We want to render created partial view in this file. Let’s see how do we do this?

Our view file contains the following source code.

// Registration.cshtml

PartialViewDemo.cshtml

The Registration page contains single text box component, the PartialViewDemo page contains second text box.

The @Html.Partial() method is used to render partial view to the Registration view.

Output:

It produces the following output when, we run the registration page.

ASP Razor partial views 2

We can submit it as a single form.

ASP Razor partial views 3

This form submits all the values to the action that are shown in the following screenshot.

ASP Razor partial views 4

You may also like