zoukankan      html  css  js  c++  java
  • JQuery和Ajax在ASP.NET MVC中的基本应用

    当我们在开发Web应用程序中使用JQueryAjax异步调用来实现很多功能时,不仅提高了程序的性能,而且给用户一个更好的交互式界面操作体验。接下来我们依旧用简单的实例来学习下它们的应用。

    创建一个ASP.NET MVC Web Application

    在Visual Studio中创建ASP.NET Web Application应用程序,在向导的下一个窗口中选择空的模板。

    创建Model

    接着我们在Models文件夹下创建一个Product类,用来传递数据。

        public class Product
        {
            public int ProductID { get; set; }
            public string ProductName { get; set; }
            public decimal Price { get; set; }
            public int Count { get; set; }
            public string Description { get; set; }
        }

    创建Controller

    Model创建好之后,接着在Controllers文件下创建一个Controller, 命名为"ProductController"。

    创建一些测试数据。

     1         public ActionResult Index()
     2         {
     3             List<Product> products = new List<Product>()
     4             {
     5                 new Product {ProductID=1,ProductName="Product A",Price=1000000,Count=5,Description="Description A"},
     6                 new Product {ProductID=2,ProductName="Product B",Price=200000,Count=2,Description="Description B"},
     7                 new Product {ProductID=3,ProductName="Product C",Price=500000,Count=8,Description="Description C"},
     8                 new Product {ProductID=4,ProductName="Product D",Price=80000,Count=10,Description="Description D"},
     9                 new Product {ProductID=5,ProductName="Product E",Price=300000,Count=3,Description="Description E"}
    10             };
    11 
    12             return View(products);
    13         }

    创建View

    然后我们在Views -> Product目录下创建一个View,命名为Index,并绑定显示Controller中的Product对象列表。

     1 @model IEnumerable<JqueryAjaxApplication.Models.Product>
     2 @{
     3     Layout = null;
     4 }
     5 
     6 <!DOCTYPE html>
     7 
     8 <html>
     9 <head>
    10     <meta name="viewport" content="width=device-width" />
    11     <title>Index</title>
    12 </head>
    13 <body>
    14     <div> 
    15         <h2 style="padding-left:5px;">Product List</h2>
    16         <table cellpadding="5" cellspacing="5" >
    17             <tr style="background-color: #7FBA00;">
    18                 <th>Product ID</th>
    19                 <th>Product Name</th>
    20                 <th>Price</th>
    21                 <th>Count</th>
    22                 <th>Description</th>
    23             </tr>
    24             @foreach (var product in Model)
    25             {
    26                 <tr style="background-color: #7FBA00; color: white;">
    27                     <td>@product.ProductID</td>
    28                     <td>@product.ProductName</td>
    29                     <td>@product.Price</td>
    30                     <td>@product.Count</td>
    31                     <td>@product.Description</td>
    32                 </tr>
    33              }
    34         </table>
    35     </div>
    36 </body>
    37 </html>

    我们看到上面使用Controller里输出,View里绑定的方式来实现列表数据的展现,接下来我们进入主题,来看看Ajax是如何实现加载列表数据等的。

    首先我们需要创建一个Partial View用来展现数据。

    编写代码如下:

     1 @using JqueryAjaxApplication.Models
     2 @model IEnumerable<Product>
     3 
     4 <div>
     5     <table cellpadding="5" cellspacing="5">
     6         <tr style="background-color: #7FBA00;">
     7             <th>Product ID</th>
     8             <th>Product Name</th>
     9             <th>Price</th>
    10             <th>Count</th>
    11             <th>Description</th>
    12         </tr>
    13         @foreach (Product product in Model)
    14         {
    15             <tr style="background-color: #7FBA00; color: white;">
    16                 <td>@product.ProductID</td>
    17                 <td>@product.ProductName</td>
    18                 <td>@product.Price</td>
    19                 <td>@product.Count</td>
    20                 <td>@product.Description</td>
    21             </tr>
    22         }
    23     </table>
    24 </div>

    相应的Controller的代码调整如下:

     1         public ActionResult Index()
     2         {
     3             return View();
     4         }
     5 
     6         public PartialViewResult Products()
     7         {
     8             return PartialView(products);
     9         }
    10 
    11         List<Product> products = new List<Product>()
    12         {
    13                 new Product {ProductID=1,ProductName="Product A",Price=1000000,Count=5,Description="Description A"},
    14                 new Product {ProductID=2,ProductName="Product B",Price=200000,Count=2,Description="Description B"},
    15                 new Product {ProductID=3,ProductName="Product C",Price=500000,Count=8,Description="Description C"},
    16                 new Product {ProductID=4,ProductName="Product D",Price=80000,Count=10,Description="Description D"},
    17                 new Product {ProductID=5,ProductName="Product E",Price=300000,Count=3,Description="Description E"}
    18         };

    使用JQuery和Ajax进行数据操作

    获取Product列表

    下面我们修改Index View,使用Ajax调用实现点击Button按钮获取Product列表的功能。

     1 @{
     2     Layout = null;
     3 }
     4 
     5 <!DOCTYPE html>
     6 
     7 <html>
     8 <head>
     9     <meta name="viewport" content="width=device-width" />
    10     <title>Index</title>
    11     <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
    12 </head>
    13 <body>
    14     <div>
    15         <div style="padding-left:5px;">
    16             <input id="btnAjax" name="btnAjax" type="button" value="Get Products" />
    17         </div> 
    18         <div id="products"></div>
    19     </div>
    20 
    21     <script>
    22         $('#btnAjax').click(function () {
    23             $.ajax({
    24                 url: '/Product/Products',
    25                 contentType: 'application/html; charset=utf-8',
    26                 type: 'GET',
    27                 dataType: 'html'
    28             })
    29             .success(function (result) {
    30                 $('#products').html(result);
    31             })
    32             .error(function (data) {
    33                 alert(data);
    34             })
    35         });
    36     </script>
    37 </body>

    点击按钮前:

    点击按钮后:

    获取单个Product信息

    Product列表数据成功加载,接着我们还想能够查看获取单条Product数据,并且能够修改Product信息,下面我们就简单实践一下。

    首先,在列表数据视图里的每条数据最右边加上一个Edit链接,修改Products Partial View代码如下:

     1 @using JqueryAjaxApplication.Models
     2 @model IEnumerable<Product>
     3 
     4 <div>
     5     <table cellpadding="5" cellspacing="5">
     6         <tr style="background-color: #7FBA00;">
     7             <th>Product ID</th>
     8             <th>Product Name</th>
     9             <th>Price</th>
    10             <th>Count</th>
    11             <th>Description</th>
    12             <th></th>
    13         </tr>
    14         @foreach (Product product in Model)
    15         {
    16             <tr style="background-color: #7FBA00; color: white;">
    17                 <td>@product.ProductID</td>
    18                 <td>@product.ProductName</td>
    19                 <td>@product.Price</td>
    20                 <td>@product.Count</td>
    21                 <td>@product.Description</td>
    22                 <td><a href="#" onclick="EditProduct(@product.ProductID)">Edit</a></td>
    23             </tr>
    24         }
    25     </table>
    26 </div>

    同时,我们在Index页面上还需要为Product的每个字段创建一个textbox,用来显示我们获取到的Product信息。并且可以修改字段信息,保存修改,修改Index页面如下:

     1      <div>
     2         <div style="padding-left:5px;">
     3             <input id="btnAjax" name="btnAjax" type="button" value="Get Products" />
     4         </div> 
     5         <div style="padding: 5px; font-weight: bold;">Product List</div>
     6         <div id="products"></div>
     7         <div id="editBlock" style="padding-top:10px;display:none;">
     8             <div style="font-weight:bold;">Edit Product</div>
     9             <table>
    10                 <tr><td>Product ID:</td><td><input id="txtProductID" name="txtProductID" type="text" disabled /></td></tr>
    11                 <tr><td> Product Name:</td><td><input id="txtProductName" name="txtProductName" type="text" /></td></tr>
    12                 <tr><td>Count:</td><td><input id="txtCount" name="txtCount" type="text" /></td></tr>
    13                 <tr><td> Price:</td><td><input id="txtPrice" name="txtPrice" type="text" /></td></tr>
    14                 <tr><td> Description:</td><td><input id="txtDescription" name="txtDescription" type="text" /></td></tr>
    15             </table>
    16             <div style="padding-top:5px;">
    17                 <div id="message" style="color:green;"></div>
    18                 <input id="btnSave" name="btnSave" type="button" value="Save" />
    19             </div>
    20         </div>
    21     </div>

     在Controller里添加获取单条Product信息的Action如下:

            public JsonResult GetProduct(int productId)
            {
                return Json(products.FirstOrDefault(p => p.ProductID == productId), JsonRequestBehavior.AllowGet);
            }

    相应的添加获取单条Productajax方法如下:

            function EditProduct(productId) {
                $("#editBlock").show();
    
                $.ajax({
                    url: '/Product/GetProduct?productId='+productId,
                    contentType: 'application/html; charset=utf-8',
                    type: 'GET'
                })
                .success(function (result) {
                    if (result != null) {
                        $("#txtProductID").val(result.ProductID);
                        $("#txtProductName").val(result.ProductName);
                        $("#txtCount").val(result.Count);
                        $("#txtPrice").val(result.Price);
                        $("#txtDescription").val(result.Description);
                    }
                })
                .error(function (data) {
                    alert(data);
                })
            }

    此时运行程序
    加载Product列表

     点击任意一条记录的Edit链接,这里我们点击第一条记录。

    保存编辑Product信息

    我们看到第一条记录的各个字段值显示到了对应的textbox中,接着我们来实现修改Product的内容,点Save按钮能保存成功,并显示到Product列表中。

    Controller里添加修改Product信息的Action,我们将修改后的结果返回给Products Partial View中。

     1         public PartialViewResult EditProduct(Product product)
     2         {
     3             foreach (var p in products)
     4             {
     5                 if (p.ProductID == product.ProductID)
     6                 {
     7                     p.ProductName = product.ProductName;
     8                     p.Count = product.Count;
     9                     p.Price = product.Price;
    10                     p.Description = product.Description;
    11                 }
    12             }
    13 
    14             return PartialView("Products", products);
    15         }

    最后,我们添加Save按钮的click事件,ajax调用上面我们创建的EditProduct Action

     1        $('#btnSave').click(function () {
     2             var product = {
     3                 ProductID: $('#txtProductID').val(), ProductName: $('#txtProductName').val(),
     4                 Count: $('#txtCount').val(), Price: $('#txtPrice').val(),
     5                 Description: $('#txtDescription').val()
     6             };
     7             $.ajax({
     8                 url: '/Product/EditProduct',
     9                 contentType: 'application/html; charset=utf-8',
    10                 data: product,
    11                 type: 'GET',
    12                 dataType:'html'
    13             })
    14             .success(function (result) {
    15                 $('#products').html(result);
    16             })
    17             .error(function (data) {
    18                 alert(data);
    19             })
    20         });

    好了,我们再次运行程序,点击Product Name为"Product A"记录的Edit链接。

    接着,我们修改以上信息,将Count改为10Price改为1200000, Description改为Description AAA,并点击Save按钮。

     

    好了,本篇就先到此,希望对你有所帮助,谢谢!

  • 相关阅读:
    Docker 学习4 Docker容器虚拟化网络概述
    Ceph 命令
    Day_09【常用API】扩展案例1_程序中使用一个长度为3的对象数组,存储用户的登录名和密码……
    Day_08【面向对象】扩展案例4_年龄为30岁的老王养了一只黑颜色的2岁的宠物……
    Day_08【面向对象】扩展案例3_使用多态的形式创建缉毒狗对象,调用缉毒方法和吼叫方法
    Day_08【面向对象】扩展案例2_测试旧手机新手机类,并给新手机实现玩游戏功能
    Day_08【面向对象】扩展案例1_测试项目经理类和程序员类
    用两个栈实现队列
    二叉树前序、中序、后序遍历相互求法
    洗牌
  • 原文地址:https://www.cnblogs.com/mejoy/p/6382746.html
Copyright © 2011-2022 走看看