日期:2014-05-16  浏览次数:20995 次

ASP.NET MVC 中实现局部更新 unobtrusive ajax
使用的是Linq to sql 对数据库进行通信的,使用表为product

首先我们要引用unobtrusive 这个js文件

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

第一步:先创建ProductControl

    public class ProductController : Controller
    {
        TestDBDataContext context = new TestDBDataContext();
        //
        // GET: /Product/

        public ActionResult Index()
        {
            var products = (from product in context.GetTable<Product>()
                           select product).ToList();
            ViewData["products"] = products;
            return View();
        }
        
        public ActionResult AddProduct(Product productModel)
        {
            productModel.CreateTime = DateTime.Now;
            context.Products.InsertOnSubmit(productModel);
            context.SubmitChanges();

            return PartialView("ProductControl1", context.Products.ToList());
        }

    }

第二步:创建VIEW 

一个partial视图(ProductControl1.cshtml)用于显示Product信息,一个是index 页面添加产品,并且Render partial view(ProductControl1.cshtml)

Index页面代码

@model MvcApp.Product

@{
    View.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
<fieldset>
<h1>Add product</h1>
@using(Ajax.BeginForm("AddProduct",new AjaxOptions{UpdateTargetId = "productList"}))
{
    <div>@Html.LabelFor(m => m.Title)</div>
    <div>@Html.EditorFor(m => m.Title)</div>
   <div>@Html.LabelFor(m => m.Price)</div>
   <div>@Html.EditorFor(m => m.Price)</div>
   <p>
   <input type="submit" value="Add Product" />
   </p>
}
</fieldset>



<div id="productList">
@{Html.RenderPartial("ProductControl1",ViewData["products"]);}
</div>

partial视图:ProductControl1页面代码

@model IEnumerable<MvcApp.Product>
<table>
<tr>
<td>Title</td>
<td>Price</td>
<td>CreateTime</td>
</tr>
@foreach(var p in Model)
{
    <tr>
    <td>@p.Title</td>
    <td>@p.Price</td>
    <td>@p.CreateTime</td>
    </tr>
}
</table>