×

iFour Logo

Best Way to Bind Partial View for Improving Performance in Asp.Net MVC

Kapil Panchal - June 23, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Best Way to Bind Partial View for Improving Performance in Asp.Net MVC

Table of Content

What is Partial View in MVC?


Partial view in Asp.Net MVC is a special type of view that returns the portion of view content. It is the same as user control of a web form application but the difference is partial view can be reusable in multiple views. It is used to help the duplication and reduce code.

ViewPart view is included with its copy of the ViewDataDictionary object available from the parent view so that partial view can access the parent view’s data.

How to create a Partial View in Asp.Net MVC?


Show in the figure how to create the view

Home_Page

[Fig:- How to create Partial View]

Partial view is a mostly reusable component so it's good practice to create a partial view inside a shared folder. The Identity that provides the built-in for a partial view is LoginPartial view and is bind in a layout file.

To create a partial view, select, create as a partial view option

Home_Page

[Fig:- Create Partial View]

After Creating Partial View Next is how to render partial view


You can provide a partial view of parental views with the help of HTML help methods. There are three types of partial methods:

  • @Html.Partial()

  • @ Html.RenderPartial()

  • @Html.RenderAction()


@Html.Partial()

@Html.Partial() method renders the partial view. It accepts a partial view name in the format of string as a parameter and return HtmlString

 

@Html.RenderPartial

The @Html.RenderPartial () method writes the result directly into the HTTP response stream. That is similar to @Html.Partial () except that it writes HTML results to the response stream, making this method faster. Here is the @Html.RenderPartial code

 

@Html.RenderAction()

@ Html.RenderAction () method uses the action method and gives results. Action method should be marked with the [ChildActionOnly] annotation and retrieve PartialviewResult using the PartialView () method.

To give a partial view using the RenderAction () method, first, create an [HttpGet] action method and use the ChildActionOnly icon as shown below.

  public class HomeController: Controller
{
    [ChildActionOnly]
    public ActionResult LoginMenu()
    {
        return PartialView("_LoginPartial");
    }
}

You can now call @Html.RenderAction () in your Structure code as shown below.

 

Bind partial View For Improving Performance


here are various ways to bind partial view and show it to a viewer. But what is the best way to capture a view that is part of improving the performance of our website?

There are several ways to bind the partial view to data from a database or static data. There are some examples to bind the partial view to data.

To Bind Some static data with the partial view as shown below

  @Html.Partial(“MenuBar”)

We can also bind partial view directly from a model.

  @Html.Partial(“Article” ,Model.Article)

We can also bind partial view with ViewBag.

  @Html.Partial(“_Article” ,(double)@ViewBag.Name)

What are the ways to bind a partial view?


The first way to tie a partial look

Binding all the partial views into one request. Try to get all the partial view data as an entity on an action result and restore the view with the model data. As in the following example, you can see that I need the latest Article and the Popular Article

  public class ArticleViewModel
  {
      public List RecentArticle { get; set; };
      public List PopularArticle { get; set; };
} 

But on the controller, I have utilized only one Action Result to get the data for both views.

  public ActionResult GetArticle()
    {
        var model = new ArticleViewModel();
        model.RecentArticle = _db.getRecentArticleList();
        model.PopularArticle = _db.getPopularArticleList();

        return View(model);
}
	

It reloads the whole code in a single view, I transfer multiple partial views where data appears in a single request.

  @model  PartialViewDemo.ViewModels.ArticleViewModel
@Html.RenderPartial("RecentPostPartialView", model.RecentArticle);
@Html.RenderPartial("PopularPostPartialView", model.PopularArticle);

So as per the performance aspect, this way of using a partial view is not good. If we bind a single view it will not affect our website on a performance basis.


The second way to tie a partial look

The best way is to tie multiple partial views into a single view using an Ajax call and provide all the partial views separately. Every partial view will make its request to retrieve data from the database and bind it with a partial view. Using an Ajax call, we can upload data without refreshing our page.

If we process a separate request for each view, then it will not affect the performance and loading of the site. The page will be loaded and the partial view will try to get the details in sync.

In this example, you create multiple partial views and make a separate request to retrieve data from the database.

Looking for Trusted Dot Net Development Company? Your Search ends here.


My View
 
Recent Articles
Recent Articles Loading....
Popular Articles
Popular Articles Loading....
My Controller
  public class RecentsController : Controller
    {
        private readonly IPostRepository _postRepository;
        private readonly ICategoryRepository _categoryRepository;
        public RecentsController(IPostRepository postRepository, ICategoryRepository categoryRepository)
        {
            _postRepository = postRepository;
            _categoryRepository = categoryRepository;
        }
       
        [HttpGet]
        public ActionResult RecentArticles()
        {
            var postEntity = _postRepository.GetPosts().OrderByDescending(x => x.PostUpdatedDate).Take(3).Select(x => new PostViewModel()
            {
                PostTitle = x.PostTitle,
                PostAddedDate = x.PostAddedDate,
                PostUrl = x.PostUrl,
                postCategory = _categoryRepository.GetSingleCategoryInfo(x.CategoryId)
            });
            return PartialView("RecentArticles", postEntity);
        }
        [HttpGet]
        public ActionResult PopularArticles()
        {
            var postEntity = _postRepository.GetPosts().OrderByDescending(x => x.NumberOfViews).Take(3).Select(x => new PostViewModel()
    
               {
                PostTitle = x.PostTitle,  
                PostAddedDate = x.PostAddedDate,  
                PostUrl = x.PostUrl,  
                postCategory = _categoryRepository.GetSingleCategoryInfo(x.CategoryId),  
                NumberOfViews = x.NumberOfViews
              });
            return PartialView("PopularArticles", postEntity);
        }
}
Jquery For Ajax
  function LoadRecentArticle()
{
    $.ajax
    ({
        url: "/Recents/RecentArticles",
        contentType: "application/html; charset=utf-8",
        type: "GET",
        datatype: "html",
        success: function(data)
        {
            $("#RecentArticle").html(data)
        },
        error: function()
        {
            $("#RecentArticle").html("Post Not Found")
        }
    })
}
function LoadPopularArticle()
{
    $.ajax
    ({
        url: "/Recents/PopularArticles",
        contentType: "application/html; charset=utf-8",
        type: "GET",
        datatype: "html",
        success: function(data)
        {
            $("#PopularArticle").html(data)
        },
        error: function()
        {
            $("#PopularArticle").html("Post Not Found")
        }
    })
}
$(document).ready(function()
{
    LoadRecentArticle(), LoadPopularArticle()
});

By using this method, you can increase the performance of your website. The website gets fully loaded rather than waiting for the whole content to completely load.

Conclusion: Partial View in MVC


Using a second method, we can upload our website faster. The website does not wait to upload all content using Ajax, our page is updated in accordance with the data exchange with the server and its update page without reloading whole the page.

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.

 
Best Way to Bind Partial View for Improving Performance in Asp.Net MVC Table of Content 1. What is Partial View in MVC? 2. How to create a Partial View? 3. After Creating Partial View Next is how to render a partial view 4. Bind partial View For Improving Performance 5. What are the ways to bind a partial view? 5.1.The first way to tie a partial look 5.2.The second way to tie a partial look 6. Conclusion What is Partial View in MVC? Partial view in Asp.Net MVC is a special type of view that returns the portion of view content. It is the same as user control of a web form application but the difference is partial view can be reusable in multiple views. It is used to help the duplication and reduce code. ViewPart view is included with its copy of the ViewDataDictionary object available from the parent view so that partial view can access the parent view’s data. How to create a Partial View in Asp.Net MVC? Show in the figure how to create the view [Fig:- How to create Partial View] Partial view is a mostly reusable component so it's good practice to create a partial view inside a shared folder. The Identity that provides the built-in for a partial view is LoginPartial view and is bind in a layout file. To create a partial view, select, create as a partial view option [Fig:- Create Partial View] After Creating Partial View Next is how to render partial view You can provide a partial view of parental views with the help of HTML help methods. There are three types of partial methods: @Html.Partial() @ Html.RenderPartial() @Html.RenderAction() @Html.Partial() @Html.Partial() method renders the partial view. It accepts a partial view name in the format of string as a parameter and return HtmlString   @Html.ActionLink("Home", "Index", "Home") @Html.ActionLink("About", "About", "Home") @Html.ActionLink("Contact", "Contact", "Home") @Html.Partial("_LoginPartial") Read More: What Is Tempdata And How To Use In Mvc? @Html.RenderPartial The @Html.RenderPartial () method writes the result directly into the HTTP response stream. That is similar to @Html.Partial () except that it writes HTML results to the response stream, making this method faster. Here is the @Html.RenderPartial code   @Html.ActionLink("Home", "Index", "Home") @Html.ActionLink("About", "About", "Home") @Html.ActionLink("Contact", "Contact", "Home") @{ Html.RenderPartial("_LoginPartial"); } @Html.RenderAction() @ Html.RenderAction () method uses the action method and gives results. Action method should be marked with the [ChildActionOnly] annotation and retrieve PartialviewResult using the PartialView () method. To give a partial view using the RenderAction () method, first, create an [HttpGet] action method and use the ChildActionOnly icon as shown below. public class HomeController: Controller { [ChildActionOnly] public ActionResult LoginMenu() { return PartialView("_LoginPartial"); } } You can now call @Html.RenderAction () in your Structure code as shown below.   @Html.ActionLink("Home", "Index", "Home") @Html.ActionLink("About", "About", "Home") @Html.ActionLink("Contact", "Contact", "Home") @{ Html.RenderAction("LoginMenu", "Home"); } Bind partial View For Improving Performance here are various ways to bind partial view and show it to a viewer. But what is the best way to capture a view that is part of improving the performance of our website? There are several ways to bind the partial view to data from a database or static data. There are some examples to bind the partial view to data. To Bind Some static data with the partial view as shown below @Html.Partial(“MenuBar”) We can also bind partial view directly from a model. @Html.Partial(“Article” ,Model.Article) We can also bind partial view with ViewBag. @Html.Partial(“_Article” ,(double)@ViewBag.Name) What are the ways to bind a partial view? The first way to tie a partial look Binding all the partial views into one request. Try to get all the partial view data as an entity on an action result and restore the view with the model data. As in the following example, you can see that I need the latest Article and the Popular Article public class ArticleViewModel { public List RecentArticle { get; set; }; public List PopularArticle { get; set; }; } But on the controller, I have utilized only one Action Result to get the data for both views. public ActionResult GetArticle() { var model = new ArticleViewModel(); model.RecentArticle = _db.getRecentArticleList(); model.PopularArticle = _db.getPopularArticleList(); return View(model); } It reloads the whole code in a single view, I transfer multiple partial views where data appears in a single request. @model PartialViewDemo.ViewModels.ArticleViewModel @Html.RenderPartial("RecentPostPartialView", model.RecentArticle); @Html.RenderPartial("PopularPostPartialView", model.PopularArticle); So as per the performance aspect, this way of using a partial view is not good. If we bind a single view it will not affect our website on a performance basis. The second way to tie a partial look The best way is to tie multiple partial views into a single view using an Ajax call and provide all the partial views separately. Every partial view will make its request to retrieve data from the database and bind it with a partial view. Using an Ajax call, we can upload data without refreshing our page. If we process a separate request for each view, then it will not affect the performance and loading of the site. The page will be loaded and the partial view will try to get the details in sync. In this example, you create multiple partial views and make a separate request to retrieve data from the database. Looking for Trusted Dot Net Development Company? Your Search ends here. See here My View   Recent Articles Recent Articles Loading.... Popular Articles Popular Articles Loading.... My Controller public class RecentsController : Controller { private readonly IPostRepository _postRepository; private readonly ICategoryRepository _categoryRepository; public RecentsController(IPostRepository postRepository, ICategoryRepository categoryRepository) { _postRepository = postRepository; _categoryRepository = categoryRepository; } [HttpGet] public ActionResult RecentArticles() { var postEntity = _postRepository.GetPosts().OrderByDescending(x => x.PostUpdatedDate).Take(3).Select(x => new PostViewModel() { PostTitle = x.PostTitle, PostAddedDate = x.PostAddedDate, PostUrl = x.PostUrl, postCategory = _categoryRepository.GetSingleCategoryInfo(x.CategoryId) }); return PartialView("RecentArticles", postEntity); } [HttpGet] public ActionResult PopularArticles() { var postEntity = _postRepository.GetPosts().OrderByDescending(x => x.NumberOfViews).Take(3).Select(x => new PostViewModel() { PostTitle = x.PostTitle, PostAddedDate = x.PostAddedDate, PostUrl = x.PostUrl, postCategory = _categoryRepository.GetSingleCategoryInfo(x.CategoryId), NumberOfViews = x.NumberOfViews }); return PartialView("PopularArticles", postEntity); } } Jquery For Ajax function LoadRecentArticle() { $.ajax ({ url: "/Recents/RecentArticles", contentType: "application/html; charset=utf-8", type: "GET", datatype: "html", success: function(data) { $("#RecentArticle").html(data) }, error: function() { $("#RecentArticle").html("Post Not Found") } }) } function LoadPopularArticle() { $.ajax ({ url: "/Recents/PopularArticles", contentType: "application/html; charset=utf-8", type: "GET", datatype: "html", success: function(data) { $("#PopularArticle").html(data) }, error: function() { $("#PopularArticle").html("Post Not Found") } }) } $(document).ready(function() { LoadRecentArticle(), LoadPopularArticle() }); By using this method, you can increase the performance of your website. The website gets fully loaded rather than waiting for the whole content to completely load. Conclusion: Partial View in MVC Using a second method, we can upload our website faster. The website does not wait to upload all content using Ajax, our page is updated in accordance with the data exchange with the server and its update page without reloading whole the page. 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.  
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Technical Content Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail
Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Quarkus vs Spring Boot - What’s Ideal for Modern App Development?
Quarkus vs Spring Boot - What’s Ideal for Modern App Development?

Spring Boot has long been a popular choice for developing custom Java applications. This is owing to its comprehensive features, impeccable security, and established ecosystem. Since...

Power BI Forecasting Challenges and Solutions
Power BI Forecasting Challenges and Solutions

Microsoft Power BI stands out for detailed data forecasting. By inspecting data patterns and using statistical models, Power BI provides a visual forecast of things to anticipate in...

Kotlin vs Java - Top 9 Differences CTOs Should Know
Kotlin vs Java - Top 9 Differences CTOs Should Know

Choosing the right programming language becomes crucial as it greatly influences the success of a software development project. When it comes to selecting the best programming language...