微软 jQuery Templates插件的在ASP.NET MVC 3 RC2 中 AJAX 更新表格

今天在无事,就一在看有关ASP.NET MVC3的一文章,无意中发现了微软的 Jquery Templates 插件,感觉很好,因为之前项目是ASP.NET MVC 2,我们经常要做的是添加一条数据,然后动态的更新列表,可是当时ASP.NET MVC2不支持接收JSON,所以就有不方便了,现在ASP.NET MVC 3 RC2支持接收JSON,再加微软的Jquery Templates就可以很方便的来做动态更新数据表了。然后就找了一下相关的文章看一下。

参考文章如下:

微软 jQuery Templates插件的使用

ASP.NET MVC 3 中JavaScript and AJAX 改进

下面给下Jquery Templates插件。

插件下载/Files/stalwart/jquery.tmpl.rar  

请先看上面的两篇文章,我就不重复了!

我自己也做了个例子,为了能牢记住。 

View:

代码
@{
    ViewBag.Title = "测试";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section header
{
    
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.tmpl.js")"></script>
    
<script type="text/javascript">
        $(document).ready(
function () {
            $(
"#submit").click(function () {
                
var users = { name: $("#Name").val(), website: $("#website").val() };
                $.ajax({
                    url: 
"/MoreForm/index",
                    type:
"POST",
                    data: users,
                    dataType:
"json",
                    success:
function(data){
                        $(
"#userTemplate").render(data).appendTo("#Template");
                    },
                    Error:
function(){
                        alert(
"错误");
                    }
                });
                
                
return false;
            });
        });
    
</script>
}
    
<div>
        @using (Html.BeginForm())
        {
            
<ul>
                
<li>@Html.TextBox("Name")</li>
                
<li>@Html.TextBox("website")</li>
                
<li><input id="submit" type="submit" value="submit"/></li>
            
</ul>
        }
    
</div>
        
<ul id="Template">
            
<script id="userTemplate" type="text/html">
            
<li><a href="http://${website}">${Name}</a></li>
        
</script>
        
</ul>

 Controller:

代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication2.Controllers
{
    
public class MoreFormController : Controller
    {
        
//
        
// GET: /MoreForm/

        
public ActionResult Index()
        {
            
return View();
        }

        [HttpPost]
        
public ActionResult index(FormCollection Form)
        {
            var model 
=new{ Name=Form["Name"].ToString(),
                               website
=Form["website"].ToString()
            };
            
//这里将POST过的生成JOSN
            
//同时也可以写入数据库,这里我就没作DOME
            return this.Json(model);
        }
    }
}

有了上面的代码相信大家也能理解了吧。 


原文地址:https://www.cnblogs.com/stalwart/p/1917270.html