Partial View Result in ASP.NET Core MVC

Partial View Results in ASP.NET Core MVC

In this article, I will discuss the Partial View Result in the ASP.NET Core MVC Web Application with Examples. Please read our previous article, where we discussed the basic concepts of View Result in ASP.NET Core MVC Application.

PartialViewResult in ASP.NET Core MVC

PartialViewResult in ASP.NET Core MVC is a type of action result that allows you to render and return a partial view that can be called from another view or can be served as an HTTP Request. Partial views are reusable components that can be embedded within other views, allowing us to create modular UI elements and promote code reusability.

The PartialViewResult class derives from the ActionResult base class. If you go to the definition of ViewResult class, then you will see the following signature. As you can see, it is a concrete class with a few properties overriding the ExecuteResultAsync method.

Partial View Results in ASP.NET Core MVC

How to Use PartialViewResult in ASP.NET Core MVC?

Here’s how you can use PartialViewResult in ASP.NET Core MVC:

  1. Create a Partial View: Start by creating a Razor partial view (with the .cshtml extension) in your project’s appropriate “Views” folder. Partial views typically contain a portion of HTML markup and any embedded Razor code needed to generate dynamic content.
  2. Create an Action Method: Create an action method that will return a PartialViewResult within your controller. This method will process data and pass it to the partial view.
  3. Return a Partial View: In the action method, return a PartialViewResult by calling the PartialView() method. You can pass a model object to the PartialView() method if you need to supply dynamic data to the partial view.
Example to Understand PartialViewResult in ASP.NET Core MVC:

First, create a partial view. So, go to the Views=>Shared folder and then add a partial view with the name _ProductDetailsPartialView.cshtml and then copy and paste the following code into it.

@model Product

<div class="text-left">
    <p>Product ID: @Model.Id</p>
    <p>Product Name: @Model.Name</p>
</div>
Next, modify the Home Controller as follows:

In the below example, the return type of the Index action method is PartialViewResult, and internally, the PartialView extension method returns an instance of PartialViewResult. This PartialView method will render the “ProductDetailsPartialView.cshtml” Razor partial view, and the product model will be used to populate dynamic content within the partial view.

using ActionResultInASPNETCoreMVC.Models;
using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public PartialViewResult Index()
        {
            Product product = new Product()
            {
                Id = 1,
                Name = "Test",
            };
            return PartialView("_ProductDetailsPartialView", product);
        }
    }
}

Now, run the application, and you should see the following output.

Example to Understand PartialViewResult in ASP.NET Core MVC

Now, it displays the content of that partial view without the layout page. This isn’t very useful by itself, so a more useful application might be to call this action in an AJAX scenario and display the returned view.

How to Call Action Method using jQuery AJAX in ASP.NET MVC?

Let us proceed and understand how to call the Action Method, which returns a Partial View from a regular View using the jQuery AJAX Method.

Step1: Modifying Home Controller

First, modify the Home Controller as follows. Here, we have two action methods. The Index action method returns the View Result, whereas the Details action method returns the Partial View Result.

using ActionResultInASPNETCoreMVC.Models;
using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }

        public PartialViewResult Details(int ProductId)
        {
            Product product = new Product()
            {
                Id = ProductId,
                Name = "Test Product",
            };
            return PartialView("_ProductDetailsPartialView", product);
        }
    }
}
Step2: Modify the Index Action Method

Next, modify the Index.cshtml view as follows. Here, you can see we are using jQuery AJAX to call the Details Partial Method of Home Controller. In order to use jQuery AJAX, first, we need to provide the path of the jQuery file, and here we are using jQuery CDN.

@model Product
@{
    ViewData["Title"] = "Home Page";
    Layout = null;
}

<div id="someDiv" class="text-left">
    
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        var rawdata = {'ProductId': '10'};

        $.ajax({
            type: "GET",
            url: "/Home/Details/",
            data: rawdata,
            success: function (viewHTML) {
                $("#someDiv").html(viewHTML);
            },
            error: function (errorData) { onError(errorData); }
        });
    });
</script>

Now, run the application, and you will get the output as expected. In our upcoming articles, we will discuss how we can perform the CRUD operations using jQuery AJAX.

How to Prevent the Partial Action Method from being invoked via normal GET and POST Requests?

The X-Requested-With header returns a string indicating whether it’s an Ajax request. An Ajax request will have this header set to XMLHttpRequest. This header value won’t be present for normal GET and POST requests (non-Ajax requests). So, create a Custom Attribute inheriting from ActionMethodSelectorAttribute. So, add a class file with the name AjaxOnlyAttribute.cs and then copy and paste the following code into it.

using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.Extensions.Primitives;
namespace ActionResultInASPNETCoreMVC.Models
{
    public class AjaxOnlyAttribute : ActionMethodSelectorAttribute
    {
        public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor actionDescriptor)
        {
            if (routeContext.HttpContext.Request.Headers != null &&
              routeContext.HttpContext.Request.Headers.ContainsKey("X-Requested-With") &&
              routeContext.HttpContext.Request.Headers.TryGetValue("X-Requested-With", out StringValues requestedWithHeader))
            {
                if (requestedWithHeader.Contains("XMLHttpRequest"))
                {
                    return true;
                }
            }

            return false;
        }
    }
}

Here,

  • RouteContext (RouteContext routeContext): Provides context information about the current route, including the HttpContext for the request. This allows you to access request data such as headers, query string parameters, route data, and more, which can be used to make decisions about the validity of the request for the specific action.
  • ActionDescriptor (ActionDescriptor actionDescriptor): Contains detailed information about the action method that is being considered for execution. This includes the controller name, action name, attributes applied to the action, parameters, and other metadata. This information can be used to identify the action method and make decisions based on its attributes or other characteristics.

Then decorate the AjaxOnlyAttribute with the Details action method as shown below.

using ActionResultInASPNETCoreMVC.Models;
using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }

        [AjaxOnly]
        public PartialViewResult Details(int ProductId)
        {
            Product product = new Product()
            {
                Id = ProductId,
                Name = "Test Product",
            };
            return PartialView("_ProductDetailsPartialView", product);
        }
    }
}

With the above changes in place, the Details action method can only be invoked via AJAX Request. Now, you can also directly check that the request is coming via AJAX or Not directly within the action method. For a better understanding, please modify the Home Controller as follows:

using ActionResultInASPNETCoreMVC.Models;
using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }

        [AjaxOnly]
        public PartialViewResult Details(int ProductId)
        {
            string method = HttpContext.Request.Method;

            string requestedWith =
                HttpContext.Request.Headers["X-Requested-With"];

            if (method == "POST")
            {
                if (requestedWith == "XMLHttpRequest")
                {
                    Product product = new Product()
                    {
                        Id = ProductId,
                        Name = "Test Product",
                    };
                    return PartialView("_ProductDetailsPartialView", product);
                }
            }

            //Create a Partial View to return Invalid Request
            return PartialView("_InvalidPartialView");
        }
    }
}
Advantages of Using PartialViewResult in ASP.NET Core MVC:

In ASP.NET Core MVC, a PartialViewResult is a type of action result that allows you to render a partial view and return the rendered content as part of a larger view. Here are some advantages of using PartialViewResult in ASP.NET Core MVC:

  • Modularity and Reusability: Partial views are designed to be modular components that can be reused across multiple views and even within different parts of the application. This promotes code reusability and helps in adhering to the DRY (Don’t Repeat Yourself) principle.
  • Encapsulation: You can encapsulate specific parts of the view logic or UI components into separate files with partial views. This makes managing and maintaining your codebase easier, as changes to a particular UI component only need to be made in one place.
  • Separation of Concerns: By using partial views, you can separate different concerns of your application’s UI into distinct partial view files. For example, you can have separate partial views for headers, footers, sidebars, and more. This separation helps in maintaining a clear and organized codebase.
  • Performance: When using partial views, you can load and render only the parts of the view that are necessary for a specific context. This can lead to improved performance, as unnecessary rendering and data processing are avoided.
  • Conditional Rendering: You can use partial views to conditionally render certain parts of the UI based on business logic or user roles. This dynamic rendering improves the user experience by tailoring the UI to the specific situation.
  • Simplified Maintenance: Since each partial view is a separate file, making changes to one part of the UI doesn’t require touching the entire view. This reduces the risk of introducing unintended bugs and simplifies maintenance tasks.
  • Composite Views: Partial views allow you to build composite views by combining different partial views together. This makes it easier to create complex views by assembling smaller, manageable components.
Disadvantages of Using PartialViewResult in ASP.NET Core MVC

While PartialViewResult in ASP.NET Core MVC offers various advantages, there are also some potential disadvantages to consider when using partial views:

  • Increased Complexity: Introducing partial views can lead to increased complexity in your application’s codebase. Managing a large number of partial views and ensuring they interact correctly with each other can become challenging.
  • Potential for Overuse: While partial views can be beneficial, overusing them can lead to overly fragmented code and difficulty in understanding the flow of the application. Care should be taken to strike a balance between modularity and readability.
  • Performance Concerns: While partial views can improve performance by loading only necessary components, excessive use of partial views can result in increased server-side processing and network requests, potentially impacting overall performance.
  • Maintenance Overhead: While partial views promote modularity, they also introduce the need to manage and maintain multiple view files. Changes made to one partial view might need corresponding adjustments in other parts of the application to maintain consistency.
  • Debugging Complexity: Debugging can become more complex when dealing with multiple layers of partial views. Tracking down issues in the rendering or interaction between different components can be challenging.
  • Increased HTTP Requests: If partial views are loaded asynchronously, they might result in additional HTTP requests to the server, which can impact page load times, especially in scenarios with slow network connections.
Use Cases of Partial View Results in ASP.NET Core MVC:

Partial View Results in ASP.NET Core MVC are used to render a portion of a view as a separate reusable component. They are particularly useful for scenarios where you want to create reusable UI components that can be included in multiple views. Here are some common use cases for Partial View Results:

  1. Modular UI Components: Partial views allow you to create modular UI components that can be reused across different views. For example, you can create a partial view for a navigation menu, header, footer, sidebar, or any other UI element that appears consistently across multiple pages.
  2. Widgetization: Partial views are ideal for creating widgets or dashboard-like components. These widgets can display information such as recent posts, latest news, weather updates, or any other dynamic content that needs to be displayed in multiple places.
  3. Dynamic Lists: If you have lists of data that need to be displayed in various views, you can create a partial view to render the list items. This can include things like comments, products, notifications, or user activities.
  4. Forms and Inputs: You can create partial views for forms and input elements that are used in different parts of your application. This can help maintain consistency in form layouts and validations.
  5. Complex UI Elements: When you have complex UI elements that involve multiple HTML elements, CSS, and JavaScript interactions, you can encapsulate them in a partial view to keep your main views cleaner and more focused.
  6. Reusable Layout Elements: Partial views can be used to define reusable layout elements that are shared across different pages. This can include content sections, sidebars, or even entire layouts with predefined structures.

In the next article, I am going to discuss the JSON Result in ASP.NET Core MVC Applications. In this article, I try to explain the Partial View Result in ASP.NET Core MVC Application with Examples. I hope you enjoy this Partial View Result in ASP.NET Core MVC Application article.

Leave a Reply

Your email address will not be published. Required fields are marked *