Click here to Skip to main content
Click here to Skip to main content

Load Clean HTML Fragments using jQuery and MVC

, 3 Dec 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
This article presents a simple method to load clean HTML fragments from the web servers using jQuery and MVC.

Introduction

This article presents a simple method to load clean HTML fragments from the web servers using jQuery and MVC.

Background

One of the great features from "jQuery" is to load some HTML fragments from the server and insert them into web pages. But most of the methods to create HTML contents are designed to create HTML pages, which are most likely to have HTML tags like "<body>" and "<head>". If you take a look at my earlier article, "A Working Example of Five Different Ways to Make jQuery AJAX Calls", you may notice that in order to generate a clean HTML fragment I wrote some pretty "ugly" code and used "HttpResponse.OutputStream()" to send the HTML content to the web browsers. As a matter of fact, this is a much simpler task when "MVC" "ViewUserControl" is used. This article will use a simple example to show you how to generate clean HTML fragments and how to load them into the web pages.

SolutionExplorer.JPG

The attached Visual Studio solution has a simple "MVC 2" web application "jQueryPartialView", which has the following major components:

  • "ApplicationModel.cs" implements the application's data model.
  • "HomeController.cs" implements the "MVC" application's "Controller".
  • "Index.aspx" is the application's main web page.
  • "LoadStudents.ascx" is the "MVC" "ViewUserControl" that generates the HTML fragments, which will be loaded by the "javascript" code implemented in the "Index.aspx".

The Visual Studio solution is created in Visual Studio 2010 and the "jQuery" version is "1.4.4". In this article, I will first introduce the data model and the "MVC" "Controller". I will then show you how the "LoadStudents.ascx" is implemented. After that, I will talk about how the HTML fragment is loaded into the "Index.aspx" page. Let us first take a look at the data model.

The Data Model

The data model in this application is implemented in the "ApplicationModel.cs" file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace jQueryPartialView.Models
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Score { get; set; }
        public DateTime GraduationTime { get; set; }
    }
}

This is probably the simplest data model for any applications. It has only one class "Student". This class will be used by the "LoadStudents.ascx" to generate a clean HTTP fragment of an HTTP 'table' that has the information of a "List" of "Student" objects.

The "MVC" Controller

The "MVC" "Controller" is implemented in the "HomeController.cs" file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using jQueryPartialView.Models;
 
namespace jQueryPartialView.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            return View();
        }
 
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult LoadStudents(int NoOfStudents)
        {
            List<Student> Students = new List<Student>();
 
            Random rd = new Random();
            for (int i = 1; i <= NoOfStudents; i++)
            {
                Student student = new Student();
                student.ID = i;
                student.Name = "Name No." + i.ToString();
                student.Score = Convert.ToInt16(60 + rd.NextDouble() * 40);
                student.GraduationTime = DateTime.Now;
 
                Students.Add(student);
            }
 
            return View(Students);
        }
    }
}

In this controller, two "ActionResult" methods are implemented:

  • The "Index" method loads the application's main web page "view" "Index.aspx"
  • The "LoadStudents" method loads the "ViewUserControl" "LoadStudents.ascx". This method takes the input parameter "NoOfStudents" and creates a "List" of randomly generated "Student" objects. The "List" is passed to "LoadStudents.ascx" as the view model.

The "ViewUserControl" "LoadStudents.ascx"

The "ViewUserControl" "LoadStudents.ascx" is used to generate the clean HTML fragments in this application:

<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Student>>" %>
<table cellspacing="0px" cellpadding="4px">
    <tr>
        <th>ID</th><th>Name</th><th>Score</th><th>GraduationTime</th>
    </tr>
<% foreach (var item in Model) { %>
    <tr>
        <td><%: item.ID %></td>
        <td><%: item.Name %></td>
        <td><%: item.Score %></td>
        <td><%: item.GraduationTime.ToShortDateString() %></td>
    </tr>
<% } %>
</table>

If you compare this "ViewUserControl" and the "ugly" code used in "A Working Example of Five Different Ways to Make jQuery AJAX Calls" to generate HTML fragments, you will be surprised by its simplicity. This is a "strong typed" "ViewUserControl". It takes a "List" of "Student" objects and loops through it to generate an HTML fragment of an HTML "table". This HTML fragment generated here will be loaded by the "javascript" code in the "Index.aspx" page.

The Application's Main Web Page "Index.aspx"

The application's main web page is "Index.aspx". The HTML fragments generated by "LoadStudents.ascx" is loaded into this page by "javascript" using "jQuery".

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Load clean html fragment</title>
    <link rel="stylesheet"
        href="<%: Url.Content("~/Content/Styles/Site.css") %>"
        type="text/css" />
    <link rel="stylesheet"
        href="<%: Url.Content("~/Content/Styles/TableStyle.css") %>"
        type="text/css" />
 
    <script src='<%: Url.Content("~/Content/Scripts/jquery-1.4.4.min.js") %>'
        type="text/javascript">
    </script>
</head>
<body>
    <div id="MainContainer">
        <div id="InputTrigger">
            <span>Please select the number of the students to retrieve</span>
            <span>
                <select id="selNoOfStudents">
                    <option>***</option>
                    <option>1</option>
                    <option>5</option>
                    <option>10</option>
                    <option>20</option>
                    <option>100</option>
                </select>
            </span>
            <img id="imgGetStudents"
                src="<%: Url.Content("~/Content/Images/arrow.png") %>"
                    alt="" />
        </div>
        <div id="HTMLContent"></div>
    </div>
</body>
</html>
 
<script type="text/javascript">
    var aquireStudentsURL = '<%: Url.Action("LoadStudents", "Home") %>';
    var ajaxLoadImgURL = '<%: Url.Content("~/Content/Images/ajax-load.gif") %>';
    $(document).ready(function () {
        var $MainContent = $("#HTMLContent");
        var $selNumberOfStudents = $("#selNoOfStudents");
        var ajaxLoadImg = "<img src='" + ajaxLoadImgURL + "' alt='Loading ...'/>";
 
        $("#imgGetStudents").click(function (e) {
            e.preventDefault();
            var numberOfStudents = $selNumberOfStudents.val();
            if (numberOfStudents == "***") {
                alert("Please select the number of the students to retrieve");
                return;
            }
 
            var resourceURL = aquireStudentsURL + "?NoOfStudents=" + numberOfStudents;
            $MainContent.html(ajaxLoadImg);
            $.ajax({
                cache: false,
                type: "GET",
                async: false,
                url: resourceURL,
                dataType: "text/html",
                success: function (htmlFragment) {
                    $MainContent.html(htmlFragment);
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        });
 
        $selNumberOfStudents.change(function () {
            $MainContent.html("");
        });
    });
</script>

This web page is a simple "view" page. The major HTML components are the following:

  • The "<select>" control "selNoOfStudents" allows the user to select the number of the students to retrieve from the "ViewUserControl" "LoadStudents.ascx".
  • The "<img>" control "imgGetStudents" displays the picture "arrow.png". This picture is a green arrowhead, which is used as a "button" in this application. Clicking on this picture will trigger an "ajax" call to load the HTML fragment generated from "LoadStudents.ascx" according to the number of the students from the "selNoOfStudents" dropdown box.
  • If the "ajax" call is successful, the received HTML fragment is inserted into the "<div>" "HTMLContent".

The "javascript" section of "Index.aspx" is also very simple. In the "$(document).load()" event, the click event of the "<img>" "imgGetStudents" is registered. When the "imgGetStudents" is clicked, the JavaScript code first obtains the number of the students to retrieve from the "<select>" control "selNoOfStudents" and then issues the "ajax" call to the server. Upon receiving of the HTML fragment, the content in the "<div>" "HTMLContent" is updated to show the information of the received students.

Run the Application

Now we finish this simple "MVC" web application and we are ready to test run it. When this web application first loads, the "Index.aspx" is shown in the web browser. We can see that the screen area specified by the "<div>" "HTMLContent" is empty.

RunApplicationStart.JPG

Select the number of the students to retrieve and click the arrowhead image, an "ajax" call is triggered to load the HTML fragment from the "ViewUserControl" "LoadStudents.ascx". The following picture shows the screen when 100 students are received:

RunApplicationLoad.JPG

I took a look at the network traffic using "Fiddler". The HTML fragment generated by "LoadStudents.ascx" is indeed clean. The following is the HTTP content captured by "Fiddler" when a single student is loaded:

RunApplicationFiddler.JPG

Points of Interest

  • This article presents a simple method to load clean HTML fragments from the web servers using "jQuery " and "MVC".
  • There are many ways to generate HTML fragments and the one used in this article should be one of the "simplest".
  • I hope that you like my postings and I hope that this article can help you one way or the other.

History

  • This is the first revision of this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dr. Song Li

United States United States
I have been working in the IT industry for some time. It is still exciting and I am still learning. I am a happy and honest person, and I want to be your friend.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberKevin Jensen4-Dec-10 5:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 3 Dec 2010
Article Copyright 2010 by Dr. Song Li
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid