ASP.NET MVC, jQuery, JSON and jTemplates example
I recently tried MVC, jQuery, JSON and jTemplates on a test project. When combined together these technologies can be very powerful. Here is the example -
I was using:
- ASP.NET MVC 2 (http://www.asp.net/mvc)
- jQuery 1.4.2 (http://code.jquery.com/jquery-1.4.2.min.js)
- JSON
- jTemplates 0.7.8 (http://jtemplates.tpython.com/)
Model
using System;
namespace MvcApplication1.Models
{
[Serializable()]
public class Employee
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? UpdatedOn { get; set; }
}
}
Controller
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Index(string SortBy)
{
var result = new List<Employee>
{
new Employee
{
Id = Guid.NewGuid(),
Name = "Employee 1",
Title = "Title 1",
CreatedOn = DateTime.Now,
UpdatedOn = DateTime.Now
},
new Employee{
Id = Guid.NewGuid(),
Name = "Employee 2",
Title = "",
CreatedOn = DateTime.Now,
UpdatedOn = DateTime.Now
},
new Employee{
Id = Guid.NewGuid(),
Name = "Employee 3",
Title = "Title 3",
CreatedOn = DateTime.Now,
UpdatedOn = null
}
};
return Json(result);
}
}
}
View
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-jtemplates.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.ajax({
url: "/Home/Index",
type: "POST",
dataType: "json",
data: {
SortyBy: ""
},
success: function (result) {
$("#employees").setTemplateElement("employeetemplate");
$("#employees").processTemplate(result);
}
});
});
function JsonStrToDtStr(jsonDate) {
if (jsonDate == null) return "";
var dt = new Date(parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
</script>
<!-- Result gets injected here -->
<div id="employees">
</div>
<!-- Template for Employees -->
<p style="display: none">
<textarea id="employeetemplate" rows="0" cols="0"><!--
<table>
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>Title</td>
<td>Created On</td>
<td>Updated On</td>
</tr>
</thead>
<tbody>
{#foreach $T as employee}
<tr>
<td>{$T.employee.Id}</td>
<td>{$T.employee.Name}</td>
<td>{$T.employee.Title}</td>
<td>{JsonStrToDtStr($T.employee.CreatedOn)}</td>
<td>{JsonStrToDtStr($T.employee.UpdatedOn)}</td>
</tr>
{#/for}
</tbody>
</table>
--></textarea></p>
</asp:Content>
Advertisement
leave a comment