Back to: ASP.NET Core Tutorials For Beginners and Professionals
Partial View Results in ASP.NET Core MVC
In this article, I am going to 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.
Returning a Partial View instead of a View from an Action Method in the ASP.NET Core MVC Application is also possible. The Partial View Result in ASP.NET Core MVC is returning the result to a Partial View Page. A partial view is one of the views that we can call inside a normal view page.
How to Use PartialViewResult in ASP.NET Core MVC?
Here’s how you can use PartialViewResult in ASP.NET Core MVC:
- 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.
- 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.
- 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 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.
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 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 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; } } }
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.
- Parallel Development: Using partial views enables different developers or teams to work on different parts of a view simultaneously. This promotes parallel development and collaboration, especially in larger projects.
- 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.
- Testing: Separating UI components into partial views can make unit testing easier. You can write tests specifically for individual components without needing to load the entire view.
- 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.
- Enhanced Flexibility: By using partial views, you have the flexibility to mix and match different components and layouts to achieve various visual arrangements and adapt to changing requirements.
In summary, PartialViewResult in ASP.NET Core MVC provides numerous advantages related to code organization, reusability, modularity, performance optimization, and improved collaboration among development teams. It’s a powerful tool for building maintainable and scalable web applications.
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.
- Testing Challenges: Unit testing can be complicated when you have interdependencies between various partial views. Ensuring proper isolation for testing each component might require extra effort.
- Possible Inefficiencies: Overly granular partial views might lead to inefficient rendering and data fetching, as each partial view might make separate data requests instead of optimizing data retrieval.
- Learning Curve for Developers: Introducing partial views might require developers to understand how to manage and utilize them properly. This could lead to a learning curve for new team members or those less familiar with the concept.
- 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.
- Rendering Logic Complexity: If not organized properly, partial views might lead to rendering logic scattered across different files, making it harder to follow the flow of the application’s UI logic.
- HTML Fragmentation: Excessive use of partial views can result in HTML fragmentation, where the structure of the rendered page might not be intuitive due to the distributed nature of partial views.
- UI Consistency: Maintaining consistent styling and UI behavior across different partial views can be a challenge, as styling and scripts might need to be managed separately for each partial view.
In summary, while partial views offer several benefits in terms of modularity and reusability, they can also introduce complexities, potential performance issues, and challenges related to maintenance and debugging. Careful consideration should be given to the appropriate use of partial views within an ASP.NET Core MVC application to strike a balance between the advantages and disadvantages they bring.
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:
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- Responsive Design: Partial views can aid in implementing responsive design by creating components that adapt to different screen sizes or device types.
- Different View Engines: If your application uses multiple view engines (e.g., Razor and Angular), partial views can help integrate these technologies within a unified MVC framework.
- Widget Libraries: You can build a library of reusable partial views that developers in your organization can use to assemble new views without duplicating code quickly.
- Third-Party Integrations: When integrating third-party components or widgets, partial views can provide a standardized way to include and manage these components in your application.
In summary, Partial View Results in ASP.NET Core MVC are versatile tools for creating reusable UI components, improving maintainability, and ensuring consistent design patterns throughout your application. They help you avoid code duplication and promote modular development practices.
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.