Back to: ASP.NET MVC Tutorial For Beginners and Professionals
Partial Views in ASP.NET MVC Application
In this article, I am going to discuss Partial Views in ASP.NET MVC Application. Please read our previous section articles where we discussed Action Results in ASP.NET MVC Application. At the end of this article, you will understand what Partial Views in MVC are, Why do we need partial Views, and how to implement Partial Views in the ASP.NET MVC Application with Examples.
Why do we need Partial Views in the ASP.NET MVC Application? or When Should I Use Partial Views?
We need to develop a partial view when we need a common part of the user interface on multiple pages in a web application. A partial view is a regular view that can be used multiple times in an application and has the file extension .cshtml.
Sometimes we also use a partial view to divide a web page into small parts such as header, footer, and menu on Layout. Other examples are comments on the blogging site, shipping and billing address in the invoice on an e-commerce site, etc.
If you are coming from an ASP.NET Web Forms background, then you can compare the Partial views in the ASP.NET MVC Application with user controls in the ASP.NET Web Forms application. That means a Partial View is like user control in ASP.NET Web Forms that are used for code re-usability purposes. Partial views help us to reduce code duplication. Hence partial views are reusable views like Header and Footer views.
What are Partial Views in MVC Application?
The Partial Views in ASP.NET MVC Application are the views that are rendered within another view. The HTML output generated by the partial view is rendered into the calling (or parent) view. Like views, partial views use the .cshtml file extension.
How Can We Call/Display a Partial View?
We can call or display a partial view within a view mainly in five ways. They are as follows:
- Html.RenderPartial
- Html.Partial
- Html.RenderAction
- Html.Action
- jQuery load function
Example to Understand Partial Views in ASP.NET MVC Application.
Let us understand Partial Views in ASP.NET MVC Application with an example. It is a common task in Web Applications to use the same code repeatedly to display/render information and details for their domain objects. For example, an e-shop Web Application would probably render each product in the same way on all web pages. Consider the following product class.
public class Product { public long ProductID { get; set; } public string Name { get; set; } public string Category { get; set; } public string Description { get; set; } public decimal Price { get; set; } }
The View for rendering the list of products in ASP.NET MVC View would be something like the one below.
@foreach (var product in Model) { <div> ID: <span>@product.ProductID</span> Name: <span>@product.Name</span> Category: <span>@product.Category</span> Description: <span>@product.Description</span> Price: <span>@product.Price</span> </div> }
This is just a simple Product class for demonstration purposes. What if we wanted to display objects with twenty or even more properties? And what if we needed to display this information on many pages in our application? Writing the same code repeatedly would be time-consuming and error-prone, and maintenance becomes a headache; if we want to do any modification, we need to do it in all places. This is where Partial Views Comes into the picture in ASP.NET MVC Application.
Create an ASP.NET MVC Application and understand the power of Partial Views.
Create a new ASP.NET Web Application named “PartialViewInMVC” and click the OK button, as shown in the image below.
Once you click on OK, it will open the “New ASP.NET Web Application” window to select the Project Template. In this window, choose the Empty template and check the MVC checkbox, then click on the OK button as shown in the below image.
Once you click on the OK button, it will create an empty ASP.NET MVC 5 Project.
Creating Model:
Add a new class file with the name Product.cs within the Models folder and then copy and paste the following code into it.
namespace PartialViewInMVC.Models { public class Product { public long ProductID { get; set; } public string Name { get; set; } public string Category { get; set; } public string Description { get; set; } public decimal Price { get; set; } } }
Creating Controller:
Add a new Controller named “ProductController” in the Controllers folder, choose the Empty MVC5 Controller template, and click on ADD button as shown in the below image.
In the next screen, provide the controller name as ProductController and click the Add button as shown in the image below.
Once the ProductController is created, copy and paste the following code.
public class ProductController : Controller { public ActionResult Index() { List<Product> products = new List<Product>() { new Product { ProductID =1, Name ="Product 1", Category = "Category 1", Description ="Description 1", Price = 10m}, new Product { ProductID =2, Name ="Product 2", Category = "Category 1", Description ="Description 2", Price = 20m}, new Product { ProductID =3, Name ="Product 3", Category = "Category 1", Description ="Description 3", Price = 30m}, new Product { ProductID =4, Name ="Product 4", Category = "Category 2", Description ="Description 4", Price = 40m}, new Product { ProductID =5, Name ="Product 5", Category = "Category 2", Description ="Description 5", Price = 50m}, new Product { ProductID =6, Name ="Product 6", Category = "Category 2", Description ="Description 6", Price = 50m} }; return View(products); } }
Creating View:
Right-click inside the Index action method and then select the “Add view” option from the context menu, provide the following details, and click the Add button as shown in the image below.
Once the Index View is created, copy and paste the following code.
@model IEnumerable<PartialViewInMVC.Models.Product> @{ ViewBag.Title = "Index"; } <h2>Product List</h2> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.ProductID) </th> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Category) </th> <th> @Html.DisplayNameFor(model => model.Description) </th> <th> @Html.DisplayNameFor(model => model.Price) </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.ProductID) </td> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Category) </td> <td> @Html.DisplayFor(modelItem => item.Description) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> </tr> } </table>
Change the default controller in the RouteConfig.cs file from Home to Product, as shown below.
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Product", action = "Index", id = UrlParameter.Optional } ); } }
Now, build and run your application and navigates to Product/Index, and you should get the following output.
When we need a section of a web page (both the Razor tags and HTML markup) in several different places, we create and use them as Partial Views.
How Partial Views are Created in ASP.NET MVC Application?
Right-click on the /Views/Shared folder, Select Add -> View option from the context menu and then provide the following details.
- View Name = ProductDetails
- Template = List
- Model Class = Product (PartialViewInMVC.Models)
- Check the Create a partial View check box and click the Add button, as shown in the image below.
Copy and paste the following code once the ProductDetails Partial View is created.
@model IEnumerable<PartialViewInMVC.Models.Product> <div class="container"> <div class="col-md-6"> <h2>Product List</h2> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.ProductID) </th> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Category) </th> <th> @Html.DisplayNameFor(model => model.Description) </th> <th> @Html.DisplayNameFor(model => model.Price) </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.ProductID) </td> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Category) </td> <td> @Html.DisplayFor(modelItem => item.Description) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> </tr> } </table> </div> </div>
How to use the Partial Views in ASP.NET MVC Application?
To use this Partial view, remove the respective code in the Index View and replace it with Html.Partial helper method is shown in the below code.
@model IEnumerable<PartialViewInMVC.Models.Product> @{ ViewBag.Title = "Index"; } @Html.Partial("ProductDetails", Model)
Now, build and run your application and see that everything is working as expected. But this time, you can re-use this partial view wherever you want, and moreover, if you decide to change how product objects are rendered, the only View you need to change is the ProductDetails partial view. The above @Html.Partial helper method passed a List<Product> object in the “ProductDetails” partial view. The partial view was dynamically rendered.
In the next article, I am going to discuss Different ways to Partial Views in ASP.NET MVC Applications. In this article, I try to explain Partial Views in ASP.NET MVC Applications with an example. I hope this Partial Views in MVC article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this Partial View in the MVC article.