This is a mirror of official site: http://jasper-net.blogspot.com/

Load Clean HTML Fragments using jQuery and MVC

| Monday, December 6, 2010
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.

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:

Collapse
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.

Read more: Codeproject

Posted via email from .NET Info

0 comments: