MSDN Tutorials

Advanced ASP.NET Core MVC: Mastering Partial Views

Partial views are a powerful feature in ASP.NET Core MVC that allow you to break down your UI into smaller, reusable components. This promotes code organization, maintainability, and a more modular approach to web development.

What are Partial Views?

A partial view is essentially a Razor view without a layout. They are rendered within other views to display specific portions of content. Think of them as reusable UI snippets that can be invoked from different parts of your application.

Why Use Partial Views?

Creating a Simple Partial View

To create a partial view, simply create a Razor view file (e.g., _ProductInfo.cshtml) in your Views/Shared folder or a specific view folder. The underscore prefix (_) is a convention to denote partial views, though it's not strictly required.

Example: Views/Shared/_ProductInfo.cshtml

<div class="product-details">
    <h4>@Model.Name</h4>
    <p>Price: $@Model.Price.ToString("N2")</p>
    <p>@Model.Description</p>
</div>

Example: Rendering in a Main View

You can render a partial view using the Html.Partial() or @{ await Html.RenderPartialAsync("_ProductInfo", Model.CurrentProduct); } helper methods.

@* Views/Products/Details.cshtml *@
@model ProductDetailsViewModel

<h2>Product Details</h2>

@* Render the partial view with the product data *@
@Html.Partial("_ProductInfo", Model.Product)@

<!-- Or using async for potentially long-running operations -->
@{ await Html.RenderPartialAsync("_ProductInfo", Model.RelatedProduct); }@

Passing Data to Partial Views

You can pass data to a partial view using:

Using Anonymous Objects

This is useful for passing specific, smaller pieces of data without creating a dedicated ViewModel.

@* In your Controller *@
public IActionResult ProductDetails(int id)
{
    var product = GetProductById(id);
    var viewModel = new ProductDetailsViewModel { Product = product };
    return View(viewModel);
}

@* In your View (Views/Products/Details.cshtml) *@
@Html.Partial("_ProductDetailsSummary", new { ProductName = Model.Product.Name, ProductPrice = Model.Product.Price })@

@* Partial View: Views/Shared/_ProductDetailsSummary.cshtml *@
@model dynamic@
<div class="summary">
    <h5>@Model.ProductName@</h5>
    <p>Current Price: @Model.ProductPrice@</p>
</div>

AJAX and Partial Views

Partial views are ideal for updating specific parts of a page using AJAX. You can define an action method that returns a partial view, and then use JavaScript to trigger this action and replace content on the client side.

Example: AJAX-enabled List Refresh

Controller Action (e.g., ProductsController.cs):

public IActionResult _ProductList()
{
    var products = _productService.GetAllProducts();
    return PartialView("_ProductListPartial", products);
}

Partial View (e.g., Views/Products/_ProductListPartial.cshtml):

@* Views/Products/_ProductListPartial.cshtml *@
@model IEnumerable<Product>

<table class="table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var product in Model)
        {
            <tr>
                <td>@product.Name@</td>
                <td>@product.Price.ToString("C")@</td>
            </tr>
        }
    </tbody>
</table>

Main View with AJAX Call (e.g., Views/Products/Index.cshtml):

@* Views/Products/Index.cshtml *@
@section Scripts {
<script>
    $(document).ready(function () {
        // Load the initial product list
        loadProductList();

        // Example: Refresh button
        $('#refreshButton').on('click', function() {
            loadProductList();
        });
    });

    function loadProductList() {
        $.ajax({
            url: '@Url.Action("_ProductList", "Products")',
            type: 'GET',
            success: function(result) {
                $('#productListContainer').html(result);
            },
            error: function() {
                $('#productListContainer').html('<p>Error loading products.</p>');
            }
        });
    }
</script>
}@

<h2>Our Products</h2>
<button id="refreshButton" class="btn btn-primary">Refresh List</button>

<div id="productListContainer">
    <!-- Product list will be loaded here by AJAX -->
</div>

View Components vs. Partial Views

While both are used for UI modularity, View Components are more powerful for complex scenarios. They are self-contained units with their own C# code, offering better separation of concerns and testability. Partial views are simpler and best suited for presentational logic and reusable UI snippets without complex business logic.

By effectively utilizing partial views, you can build more organized, maintainable, and dynamic web applications with ASP.NET Core MVC.