加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

MVC 中 使用unobtrusive ajax 局部更新

发布时间:2020-12-16 00:15:51 所属栏目:百科 来源:网络整理
导读:我使用的是Linq to sql 对数据库进行通信的,使用表为product 首先我们要引用unobtrusive这个js文件 [html] view plain copy script src = "@Url.Content(" ~/Scripts/jquery.unobtrusive-ajax.min.js")" type = "text/javascript" / script 1.先创建Product

我使用的是Linq to sql 对数据库进行通信的,使用表为product

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

[html] view plain copy
  1. <scriptsrc="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"type="text/javascript"></script>

1.先创建ProductControl

[csharp] view plain copy
  1. publicclassProductController:Controller
  2. {
  3. TestDBDataContextcontext=newTestDBDataContext();
  4. //
  5. //GET:/Product/
  6. publicActionResultIndex()
  7. {
  8. varproducts=(fromproductincontext.GetTable<Product>()
  9. selectproduct).ToList();
  10. ViewData["products"]=products;
  11. returnView();
  12. }
  13. publicActionResultAddProduct(ProductproductModel)
  14. {
  15. productModel.CreateTime=DateTime.Now;
  16. context.Products.InsertOnSubmit(productModel);
  17. context.SubmitChanges();
  18. returnPartialView("ProductControl1",context.Products.ToList());
  19. }
  20. }
2.创建View

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

Index页面代码

[html] view plain copy
  1. @modelMvcApp.Product
  2. @{
  3. View.Title="Index";
  4. Layout="~/Views/Shared/_Layout.cshtml";
  5. }
  6. <h2>Index</h2>
  7. <fieldset>
  8. <h1>Addproduct</h1>
  9. @using(Ajax.BeginForm("AddProduct",newAjaxOptions{UpdateTargetId="productList"}))
  10. {
  11. <div>@Html.LabelFor(m=>m.Title)</div>
  12. <div>@Html.EditorFor(m=>m.Title)</div>
  13. <div>@Html.LabelFor(m=>m.Price)</div>
  14. <div>@Html.EditorFor(m=>m.Price)</div>
  15. <p>
  16. <inputtype="submit"value="AddProduct"/>
  17. </p>
  18. }
  19. </fieldset>
  20. <divid="productList">
  21. @{Html.RenderPartial("ProductControl1",ViewData["products"]);}
  22. </div>
ProductControl1页面代码
[html] view plain copy
  1. @modelIEnumerable<MvcApp.Product>
  2. <table>
  3. <tr>
  4. <td>Title</td>
  5. <td>Price</td>
  6. <td>CreateTime</td>
  7. </tr>
  8. @foreach(varpinModel)
  9. {
  10. <tr>
  11. <td>@p.Title</td>
  12. <td>@p.Price</td>
  13. <td>@p.CreateTime</td>
  14. </tr>
  15. }
  16. </table>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读