Skip to content

4.3 Partial Views

1. Introduction

Play

ASP.NET MVC - Partial Views

In ASP.NET MVC, Partial Views are a mechanism to reuse a portion of your user interface across multiple views. They allow you to render a piece of a web page in isolation, which can be especially helpful for components like navigation menus, headers, footers, or any repeated content across your application.

Key Concepts

  1. Definition: A Partial View is similar to a View but it only renders a part of the page. Unlike a full view, partial views do not execute layout files (like _Layout.cshtml).

  2. Use Cases:

    • Reusing UI components across multiple views.
    • Reducing duplication of common content.
    • Handling small portions of content, such as forms or lists that can be updated asynchronously via AJAX.
  3. Creating a Partial View: You create a Partial View like any other view, but it is typically saved in the Views/Shared folder or within a specific controller’s view folder. The filename is something like _PartialView.cshtml.

    Example:

    <!-- _ExamplePartial.cshtml -->
    <div>
    <h2>This is a partial view</h2>
    <p>@Model.SomeProperty</p>
    </div>
  4. Rendering a Partial View: You can render a Partial View inside a parent view using either:

    • @Html.Partial() (returns the partial view as HTML).
    • @Html.RenderPartial() (writes the partial view directly into the response stream).
    • @Html.Action() or @Html.RenderAction() if the partial view has an associated action in the controller.

    Example:

    <!-- Rendering a partial view -->
    @Html.Partial("_ExamplePartial", model)
  5. Passing a Model to Partial Views: Partial views can accept models just like regular views. You can pass a specific model instance or even a subset of the parent view model to the partial view.

    Example:

    <!-- Passing a model to the partial view -->
    @Html.Partial("_ExamplePartial", new PartialViewModel { SomeProperty = "Value" })
  6. AJAX with Partial Views: Partial views are commonly used with AJAX to update parts of a page without requiring a full page reload. This can enhance user experience by making the app more responsive.

  7. Differences from Layout Views: Partial views focus on rendering fragments of HTML and don’t include common layout elements like headers or footers (which are defined in Layout views). Layout views typically define a full page structure with placeholders for content, while partial views only render specific sections.

2. Partial Views in ASP.NET

Following is a detailed example where we create and use a Partial View in an ASP.NET MVC application.

2.1 Scenario 01

Assume you need to display a list of comments under a blog post.

Step 1: Create the Partial View

We’ll create a partial view to display each individual comment. First, we’ll define a model for a comment, then create a partial view to display it.

Models/Comment.cs
public class Comment
{
public string Author { get; set; }
public string Content { get; set; }
public DateTime DatePosted { get; set; }
}

Now, create the partial view that will display a single comment.

<!-- Views/Shared/_CommentPartial.cshtml -->
@model YourNamespace.Models.Comment
<div class="comment">
<h4>@Model.Author</h4>
<p>@Model.Content</p>
<small>Posted on: @Model.DatePosted.ToShortDateString()</small>
</div>

Step 2: Create the View that will use the Partial View

Now, let’s say we have a Post view that displays a blog post and its associated comments. This is where we will render the list of comments using our partial view.

First, the model for the blog post might look something like this:

Models/Post.cs
public class Post
{
public string Title { get; set; }
public string Content { get; set; }
public List<Comment> Comments { get; set; }
}

Now, in the Post.cshtml view, we will render the list of comments by looping through the comments and using the _CommentPartial.cshtml partial view for each comment.

<!-- Views/Post/Details.cshtml -->
@model YourNamespace.Models.Post
<div class="post">
<h1>@Model.Title</h1>
<div class="post-content">
<p>@Model.Content</p>
</div>
<h3>Comments</h3>
<div class="comments">
@foreach (var comment in Model.Comments)
{
@Html.Partial("_CommentPartial", comment)
}
</div>
</div>

Step 3: Controller Logic

In the controller, we will load the Post and pass it to the Post/Details.cshtml view. Here’s an example of how the controller might look:

Controllers/PostController.cs
public class PostController : Controller
{
public ActionResult Details(int id)
{
// Sample data for demonstration
var post = new Post
{
Title = "Sample Blog Post",
Content = "This is a sample blog post content.",
Comments = new List<Comment>
{
new Comment { Author = "John", Content = "Great post!", DatePosted = DateTime.Now.AddDays(-1) },
new Comment { Author = "Jane", Content = "Thanks for sharing!", DatePosted = DateTime.Now.AddDays(-2) }
}
};
return View(post);
}
}

Step 4: Render the Partial View in the Main View

When you navigate to the post’s details page, the view will render the blog post and use the partial view to render each comment. The comments section will look like this:

<h3>Comments</h3>
<div class="comments">
<div class="comment">
<h4>John</h4>
<p>Great post!</p>
<small>Posted on: 09/25/2023</small>
</div>
<div class="comment">
<h4>Jane</h4>
<p>Thanks for sharing!</p>
<small>Posted on: 09/24/2023</small>
</div>
</div>

2.2 Key Points in This Example:

  • Reusability: The _CommentPartial.cshtml view can be reused anywhere comments need to be displayed in the app, not just on this page.
  • Modularity: Partial views make the main view cleaner by offloading the rendering logic for individual parts (like comments) into separate, smaller views.
  • Passing Models: The @Html.Partial("_CommentPartial", comment) line passes a specific Comment model to the partial view for rendering.

2.3 Optional: Using AJAX to Load Comments

Partial views are often combined with AJAX to dynamically load parts of the page without reloading the entire page. If you want to load comments asynchronously, you could:

  1. Define an action in the controller that returns the partial view:

    public ActionResult LoadComments(int postId)
    {
    var comments = GetCommentsForPost(postId); // Get comments from the database or elsewhere
    return PartialView("_CommentPartial", comments);
    }
  2. Use JavaScript to send an AJAX request to that action, and then update the page dynamically.

2.4 Scenario 02

Let’s walk through how to use AJAX with Partial Views in ASP.NET MVC. This allows us to load parts of the page dynamically without refreshing the entire page, which enhances the user experience.

Assume you need to Load comments for a blog post using AJAX. We’ll build upon the previous example where we have a list of comments under a blog post. This time, instead of loading all comments when the page is loaded, we’ll load them dynamically via an AJAX request.

Step 1: Create the Partial View for Comments

First, we’ll reuse the _CommentPartial.cshtml partial view from the previous example. This partial view will be responsible for rendering each individual comment.

<!-- Views/Shared/_CommentPartial.cshtml -->
@model YourNamespace.Models.Comment
<div class="comment">
<h4>@Model.Author</h4>
<p>@Model.Content</p>
<small>Posted on: @Model.DatePosted.ToShortDateString()</small>
</div>

Step 2: Create the Controller Action for Loading Comments

Next, we’ll create a controller action that returns the partial view containing the comments. This action will be called via AJAX, and it will only return the HTML for the comments section.

Controllers/PostController.cs
public class PostController : Controller
{
// Action to render the comments partial view via AJAX
public ActionResult LoadComments(int postId)
{
// Sample comments for demonstration
var comments = new List<Comment>
{
new Comment { Author = "John", Content = "Great post!", DatePosted = DateTime.Now.AddDays(-1) },
new Comment { Author = "Jane", Content = "Thanks for sharing!", DatePosted = DateTime.Now.AddDays(-2) }
};
// Return the partial view containing the list of comments
return PartialView("_CommentPartialList", comments);
}
}

This LoadComments action will return a partial view containing the list of comments. Notice that we use a new partial view _CommentPartialList to render the entire list of comments (as opposed to the individual comment partial _CommentPartial).

Step 3: Create a Partial View for the List of Comments

This partial view will render the entire list of comments. It will iterate through the comments and use the _CommentPartial.cshtml to render each one.

<!-- Views/Shared/_CommentPartialList.cshtml -->
@model IEnumerable<YourNamespace.Models.Comment>
<div class="comments">
@foreach (var comment in Model)
{
@Html.Partial("_CommentPartial", comment)
}
</div>

Step 4: Modify the Main View to Trigger AJAX

In the main view where the blog post is displayed, we’ll add a button to load the comments via AJAX. We’ll also include a placeholder (<div>) where the comments will be loaded.

<!-- Views/Post/Details.cshtml -->
@model YourNamespace.Models.Post
<div class="post">
<h1>@Model.Title</h1>
<div class="post-content">
<p>@Model.Content</p>
</div>
<!-- Button to load comments via AJAX -->
<button id="load-comments-btn">Load Comments</button>
<!-- Placeholder for the comments that will be loaded via AJAX -->
<div id="comments-section">
<!-- Comments will be injected here via AJAX -->
</div>
</div>
<!-- Include jQuery for making the AJAX call -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// On clicking the "Load Comments" button, trigger AJAX request
$("#load-comments-btn").click(function () {
$.ajax({
url: '@Url.Action("LoadComments", "Post", new { postId = Model.Id })',
type: 'GET',
success: function (data) {
// Inject the returned HTML (partial view) into the comments section
$("#comments-section").html(data);
},
error: function () {
alert("Error loading comments.");
}
});
});
});
</script>

Explanation of the Code:

  1. AJAX Call:

    • When the “Load Comments” button is clicked, an AJAX request is sent to the LoadComments action.
    • The URL for the AJAX request is generated using the @Url.Action() helper, which points to the LoadComments action in the PostController.
    • If the AJAX call succeeds, the returned HTML (which is the partial view with the comments) is injected into the #comments-section <div>.
  2. jQuery:

    • We use jQuery to simplify the AJAX request.
    • When the button is clicked, we use the $.ajax() function to send a GET request to the server.
    • On success, the comments HTML is inserted into the page using the $("#comments-section").html(data) method.

Step 5: Returning Partial View as Response

When the AJAX request is sent, the LoadComments action in the PostController executes. It returns the _CommentPartialList.cshtml partial view, which contains the HTML for the list of comments.

This HTML is then inserted into the #comments-section <div> in the main view.

Step 6: Result

  1. Initially, the page loads without any comments visible.
  2. When the user clicks the “Load Comments” button, the comments are loaded via AJAX and displayed on the page without a full page reload.

2.5 Example Workflow:

  • Initial Page:

    • The user sees the blog post content and the “Load Comments” button.
    • No comments are displayed initially.
  • After AJAX Load:

    • The user clicks the “Load Comments” button.
    • An AJAX request is sent to the server, which returns the list of comments in HTML.
    • The comments are dynamically added to the page without refreshing the entire page.

2.6 Optional: Loading Indicator

To improve the user experience, you could add a loading indicator to show the user that comments are being loaded. Here’s a quick way to add one:

<!-- Add a loading message before comments load -->
<div id="loading" style="display:none;">Loading comments...</div>
<script type="text/javascript">
$(document).ready(function () {
$("#load-comments-btn").click(function () {
$("#loading").show(); // Show loading message
$.ajax({
url: '@Url.Action("LoadComments", "Post", new { postId = Model.Id })',
type: 'GET',
success: function (data) {
$("#loading").hide(); // Hide loading message
$("#comments-section").html(data); // Insert comments
},
error: function () {
alert("Error loading comments.");
}
});
});
});
</script>

In this version, a “Loading comments…” message is displayed while the AJAX request is being processed.