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 ASP.NET Core MVC Applications with Examples. Please read our previous article discussing View Result in ASP.NET Core MVC Application.

PartialViewResult in ASP.NET Core MVC

In ASP.NET Core MVC, PartialViewResult is a type of action result that represents rendering a partial view to be returned to the client. A partial view is a reusable view that can be rendered within another view. They are useful for rendering common UI components like headers, footers, sidebars, or any other section of a webpage that might be reused across multiple views without duplicating code.

When you return a PartialViewResult from a controller action, ASP.NET Core MVC renders the specified partial view and returns the rendered HTML to the client. The PartialViewResult class derives from the ActionResult base class. If you go to the definition of PartialViewResult class, 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

ExecuteResultAsync Method of PartialViewResult Class:

In ASP.NET Core MVC, the ExecuteResultAsync method of the PartialViewResult class is used to render a partial view that is returned to the client as part of an HTTP response. The following are the things to happen when you return a PartialViewResult from an action method:

  • When the MVC framework executes an action that returns a PartialViewResult, it eventually calls the ExecuteResultAsync method of the PartialViewResult class.
  • Inside the ExecuteResultAsync method, the MVC framework prepares the data and context required for rendering the partial view.
  • It then finds and renders the partial view, which typically includes executing any Razor code and rendering HTML content.
  • After rendering the partial view, the generated HTML content is written to the response stream and sent back to the client as part of the HTTP response.
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: Create 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: Within your controller, create an action method that will return a PartialViewResult. 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:

Let us understand how to use PartialViewResult in ASP.NET Core MVC Application with one example. First, create a new ASP.NET Core MVC Project using the Model View Controller template and name the project ActionResultInASPNETCoreMVC.

Creating Model:

Next, create a model class to hold the product data. So, create a class file named Products.cs within the Models folder and copy and paste the following code into it.

namespace ActionResultInASPNETCoreMVC.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string? Name { get; set; }
    }
}
Creating a Partial View:

First, create a partial view. Go to the Views=>Shared folder, add a partial view with the name _ProductDetailsPartialView.cshtml, and 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>
Modify the Home Controller:

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” partial view, and the product model will 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.

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);
        }
    }
}
Modify the Index.cshtml View

Next, modify the Index.cshtml view as follows. Here, you can see we are using jQuery AJAX to call the Details Action Method of the Home Controller, which returns a Partial View. In order to use jQuery AJAX, we first 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 to perform the CRUD operations using jQuery AJAX.

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

Now, you can also access the Details Action Method, which returns a Partial View using Normal GET and Post Request.  Now, we want to restrict this. This means the Details Action Method should invoked via AJAX Request, not from general GET and Post request. For this, we need to Create a Custom Attribute, and within the Custom Attribute, we need to check whether the request is a normal GET Request or POST Request, or it is an AJAX Request. If it is a normal GET or POST request, we need to return a 404 error; if it is an AJAX Request, we need to return the data. Let us proceed and see how we can do this.

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;
        }
    }
}
Method Parameter Explanation:
  • 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): This contains detailed information about the action method 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, if you try to access the Details action method using Normal GET or POST request, you will get a 404 Error.

Checking the Request Path in the Code:

Now, you can also check whether the request is coming via AJAX directly within the action method. For a better understanding, please modify the Home Controller as follows. If the request is GET or POST, if it is coming as an AJAX request, it will return the _ProductDetailsPartialView partial view to the client, and if it is not an AJAX request, it will return the _InvalidRequestPartialView Partial view to the client.

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

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

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

            if (method == "POST" || method == "GET")
            {
                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("_InvalidRequestPartialView");
        }
    }
}
Creating _InvalidRequestPartialView:

Next, create a Partial View named _InvalidRequestPartialView within the Views/Shared folder and copy and paste the following code.

<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />

<div class="alert alert-danger" role="alert">
    <h4 class="alert-heading">Invalid Request!</h4>
    <p>Sorry, the request you submitted is invalid. Please check your input and try again.</p>
    <!-- Optionally, you can include additional details about the invalid request -->
</div>

With the above changes in place, run the application, and it should work as expected. If you access the Details action method, it will return the response. But if you access the Details action method via a normal GET request, you will get the following error message:

Partial View Result in ASP.NET Core MVC Application with Examples

In the next article, I will 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 *