Partial Views in ASP.NET MVC Application
Table of Contents
Why do we need Partial Views in the ASP.NET MVC Application?
or When Should I Use Partial Views in the ASP.NET MVC Application?.
How to create a Partial View?.
After Creating Partial View Next is how to render partial view.
Bind partial View for Improving Performance.
Partial Views in ASP.NET MVC Application
What is a Partial View?
A partial view is like as user control in Asp.Net Web forms that is used for code re-usability. Partial views helps us to reduce code duplication. Hence partial views are reusable views like as Header and Footer views.
We can use partial view to display blog comments, product category, social bookmarks buttons, a dynamic ticker, calendar etc.
Why do we need Partial Views in the ASP.NET MVC Application?
or
When Should I Use Partial Views in the ASP.NET MVC Application?
- Break up large markup files into smaller components, such as header, footer, and menu on Layout, comments on blogging site, shipping and billing address in the invoice in e-commerce site, etc.
- Reduce the duplication of common markup content across markup files. Hence partial views are reusable views like Header and Footer views.
How to create a Partial View?
A partial view has same file extension(.cshtml) as regular view. To create a partial view do right click on shared folder (\Views\Shared) in solution explorer and click on "Add New View" option and then give the name for partial view and also checked the Create a partial view option.
Note: It is best practice to create partial view in the shared folder and partial view name is preceded by "_", but it is not mandatory. The "_" before view name specify that it is a reusable component i.e. partial view.
After Creating Partial View Next is how to render partial view
A partial view is rendered by using the ViewUserControl class that is inherited/derived from the ASP.NET UserControl class.
There are several ways to bind partial views and display them on views.
We can use Partial Views in our main views by the following methods.
- Html.RenderPartial
- Html.Partial
- Html.RenderAction
- Html.Action
- jQuery load function
Bind partial View for Improving Performance
code.
<div>
@{Html.RenderPartial("_address");}
</ div>
This method generates a response as part of the same HTTP response of the main view. It uses the same TextWriter object used by the current web page.
If you have a model associated with View and the model required for partial view is part of ViewModel then RenderPartial method is ideal to use.
It works when you have partial view located in Shared. If your partial view located in different folder or in ASP.NET MVC Area then you will have to mention full path of view.
@Html.RenderPartial("~/Areas/Admin/Views/Shared/partial/_subcat.cshtml")
In this step, you will render _address partial view using Html.Partial helper method.
Open Index.cshtml and add below HTML code to it. Which adds _
<div>
@Html.Partial("_address")
</ div>
It renders _address partial view as HTML encoded string. The returned HTML encoded string can be stored in variable.
Like Html.RenderPartial it is useful when required data of partial view is a part of parent view model.
For rendering partial view using Html.RenderAction, you required Controller Action Method which returns PartialViewResult.
Open _Layout.cshtml file and add below html to it.
<div class="col-md-3">
@Html.Action("CategoryList","Home")
</div>
Open HomeController.cs file from the Controllers folder. Add below child action method with name CategoryList.
[ChildActionOnly]
public ActionResult CategoryList()
{
var dataModel= db.BookCategories.OrderBy(b=>b.Category).ToList();
return PartialView("_CategoryList", dataModel);
}
Notice that this Action Method use ChildActionOnly attribute. It is used for PartialViewResult. The action methods used with ChildActionOnly will not be used for routing browser requests. You can see more examples of the ASP.NET MVC Routing.
Like Html.RenderPartial, RenderAction also returns output to the same HTTP Response stream of the parent web page.
Html.RenderAction is useful when partial view data is independent of the parent model. For example when we display categorylist on our layout pages where category may not be related to the product.
You can render a partial view using Html.Action helper method.
Like Html.RenderAction requires controller child action method which return PartialViewResult.
Open the Index.cshtml file and add below HTML to it.
<div>
@Html.Action("GetAddressAction")
</ div>
Open HomeController.cs file from the Controllers folder. Add below action method with name GetAddressAction.
[ChildActionOnly]
public ActionResult GetAddressAction()
{
return PartialView("_address");
}
It returns HtmlString and can be saved in a variables.
Html.Action is also useful when partial view data is independent of the parent model
You can also use parameters and decide what data to provide or which Partial View to render.
Below is the example which provides billing as parameter to ActionWithParameter action method.
<div>
@Html.Action("ActionWithParameter", new { category = "billing" })
</ div>
Action method code
[ChildActionOnly]
public ActionResult ActionWithParameter(string category)
{
if(category == "billing")
return PartialView("_billingaddress");
return PartialView("_shippingaddress");
}
You can also use parameter in same way with Html.RenderAction.
Render Partial View Using jQuery
You can load your partial view using the jQuery load method. It makes ajax request to controller action method and load output in html control like div.
Add div in index.cshtml file as shown below and add a script to load the output of action method GetAddressForjQuery.
<div id="partialviews"> </div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/jscript">
$(document).ready(function () {
$("#partialviews").load('/home/GetAddressForjQuery');
});
</script>
Add controller action method
public PartialViewResult GetAddressForjQuery(string category)
{
return PartialView("_address");
}
Conclusion
Using this way, you can increase the performance of your website. Initially, the website will be loaded, and do not wait for the content that is still in the loading stage. So in short a website would simply get loaded without waiting for all the loading content.
Back to Blogs