我使用的是Linq to sql 对数据库进行通信的,使用表为product
首先我们要引用unobtrusive这个js文件
- <scriptsrc="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"type="text/javascript"></script>
1.先创建ProductControl
- publicclassProductController:Controller
- {
- TestDBDataContextcontext=newTestDBDataContext();
- //
- //GET:/Product/
- publicActionResultIndex()
- {
- varproducts=(fromproductincontext.GetTable<Product>()
- selectproduct).ToList();
- ViewData["products"]=products;
- returnView();
- }
- publicActionResultAddProduct(ProductproductModel)
- {
- productModel.CreateTime=DateTime.Now;
- context.Products.InsertOnSubmit(productModel);
- context.SubmitChanges();
- returnPartialView("ProductControl1",context.Products.ToList());
- }
- }
一个partial视图(ProductControl1.cshtml)用于显示Product信息,一个是index 页面添加产品,并且Render partial view(ProductControl1.cshtml)
- @modelMvcApp.Product
- @{
- View.Title="Index";
- Layout="~/Views/Shared/_Layout.cshtml";
- }
- <h2>Index</h2>
- <fieldset>
- <h1>Addproduct</h1>
- @using(Ajax.BeginForm("AddProduct",newAjaxOptions{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>
- <inputtype="submit"value="AddProduct"/>
- </p>
- }
- </fieldset>
- <divid="productList">
- @{Html.RenderPartial("ProductControl1",ViewData["products"]);}
- </div>
- @modelIEnumerable<MvcApp.Product>
- <table>
- <tr>
- <td>Title</td>
- <td>Price</td>
- <td>CreateTime</td>
- </tr>
- @foreach(varpinModel)
- {
- <tr>
- <td>@p.Title</td>
- <td>@p.Price</td>
- <td>@p.CreateTime</td>
- </tr>
- }
- </table>