MVC三级联动无刷新

本篇实现有关客户、订单和产品的无刷新三级联动,先看最终效果:

 

没有选择时,后2个Select状态为禁用:
MVC三级联动无刷新

 

当选择第1个Select,第2个Select可供选择,第3个Select依旧禁用:
MVC三级联动无刷新

 

当选择第2个Select,第3个Select可供选择:
MVC三级联动无刷新

 

当选择第3个Select,界面出现"显示产品信息"按钮:
MVC三级联动无刷新

 

当点击"显示产品信息"按钮,显示产品信息:
MVC三级联动无刷新

 

当点击"清空"按钮,恢复到初始状态:
MVC三级联动无刷新

 

  View Models

Model之间的关系为:
MVC三级联动无刷新

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:   
   5:  namespace MvcApplication2.Models
   6:  {
   7:      public class Customer
   8:      {
   9:          public int CustomerID { get; set; }
  10:          public string Name { get; set; }
  11:      }
  12:   
  13:      public class Order
  14:      {
  15:          public int OrderID { get; set; }
  16:          public int CustomerID { get; set; }
  17:          public DateTime OrderTime { get; set; }
  18:      }
  19:   
  20:      public class OrderDetail
  21:      {
  22:          public int OrderDetailID { get; set; }
  23:          public int OrderID { get; set; } 
  24:          public List<Product> Products { get; set; } 
  25:      }
  26:   
  27:      public class Product
  28:      {
  29:          public int ProductID { get; set; } 
  30:          [Display(Name = "产品名称")]
  31:          public string Name { get; set; }
  32:   
  33:          [Display(Name = "单价")]
  34:          public decimal UnitPrice { get; set; }
  35:      }
  36:  }
  37:   

 

  显示客户的Select

□ 服务层方法

   1:          //获取客户信息
   2:          public static List<Customer> GetCustomers()
   3:          {
   4:              List<Customer> customers = new List<Customer>();
   5:              customers.Add(new Customer(){CustomerID = 1,Name = "张三"});
   6:              customers.Add(new Customer(){CustomerID = 2, Name = "李四"});
   7:              return customers;
   8:          }

 

□ 控制器方法

   1:          public ActionResult Index()
   2:          {
   3:              List<Customer> customers =  Service.GetCustomers();
   4:              List<SelectListItem> items = new List<SelectListItem>(); 
   5:              foreach (Customer customer in customers)
   6:              {
   7:                  SelectListItem item = new SelectListItem()
   8:                  {
   9:                      Text = customer.Name,
  10:                      Value = customer.CustomerID.ToString()
  11:                  };
  12:                  items.Add(item);
  13:              }
  14:              ViewData["c"] = items;
  15:              return View();
  16:          }

 

□ 视图

客户:@Html.DropDownList("Customers", (List<SelectListItem>)ViewData["c"],"==选择客户==",new {id = "Customers"} )

 

  选择客户Select,显示订单Select

□ 服务层方法

   1:          //根据客户获取订单
   2:          public static List<Order> GetOrdersByCustomer(int customerID)
   3:          {
   4:              List<Order> orders = new List<Order>();
   5:              orders.Add(new Order(){OrderID = 1,CustomerID = 1,OrderTime = new DateTime(2014,1,2)});
   6:              orders.Add(new Order() { OrderID = 2, CustomerID = 1, OrderTime = new DateTime(2014, 1, 3) });
   7:              orders.Add(new Order() { OrderID = 3, CustomerID = 2, OrderTime = new DateTime(2014,1,4) });
   8:              orders.Add(new Order() { OrderID = 4, CustomerID = 2, OrderTime = new DateTime(2014,1,5) });
   9:   
  10:              return orders.Where(o => o.CustomerID == customerID).ToList();
  11:          }

 

□ 控制器方法

   1:          //根据客户获取订单
   2:          [HttpPost]
   3:          public JsonResult Orders(string customerID)
   4:          {
   5:              List<KeyValuePair<string,string>> items = new List<KeyValuePair<string, string>>();
   6:              if (!string.IsNullOrEmpty(customerID))
   7:              {
   8:                  var orders = Service.GetOrdersByCustomer(int.Parse(customerID));
   9:                  if (orders.Count() > 0)
  10:                  {
  11:                      foreach (Order order in orders)
  12:                      {
  13:                          items.Add(new KeyValuePair<string, string>(
  14:                              order.OrderID.ToString(),
  15:                              string.Format("{0} ({1:yyyy-MM-dd})",order.OrderID,order.OrderTime)));
  16:                      }
  17:                      
  18:                  }
  19:              }
  20:              return Json(items);
  21:          }

 

□ 视图  

   1:      <p>
   2:          客户:@Html.DropDownList("Customers", (List<SelectListItem>)ViewData["c"],"==选择客户==",new {id = "Customers"} )
   3:      </p>
   4:      <p>
   5:          订单:<select id="Orders" name="Orders">
   6:                 <option value="">==选择订单==</option>
   7:             </select> 
   8:      </p>

 

□ 视图js部分

   1:  @section scripts
   2:  {
   3:      <script type="text/javascript">
   4:          $(function () {
   5:   
   6:              //初始化
   7:              init();
   8:   
   9:              //点击客户触发
  10:              $(‘#Customers‘).change(function() {               
  11:                  changeCustomer();
  12:              });
  13:          });
  14:   
  15:          //初始化
  16:          function init() {
  17:              $(‘#ButtonSubmit‘).hide();
  18:              $(‘#Orders‘).attr("disabled", "true");
  19:              $(‘#Products‘).attr("disabled", "true");
  20:          }
  21:   
  22:          //点击客户事件
  23:          function changeCustomer() {
  24:              var selectedValue = $(‘#Customers option:selected‘).val();
  25:              if ($.trim(selectedValue).length > 0) {
  26:                  getOrders(selectedValue);
  27:              }
  28:          }
  29:   
  30:          //点击客户显示订单
  31:          function getOrders(customerID) {
  32:              $.ajax({
  33:                  url: ‘@Url.Action("Orders","Home")‘,
  34:                  data: { customerID: customerID },
  35:                  type: ‘post‘,
  36:                  cache: false,
  37:                  async: false,
  38:                  dataType: ‘json‘,
  39:                  success: function(data) {
  40:                      if (data.length > 0) {
  41:                          $(‘#Orders‘).removeAttr("disabled");
  42:                          $(‘#Orders‘).empty();
  43:                          $(‘#Orders‘).append($(‘<option></option>‘).val(‘‘).text(‘==选择订单==‘));
  44:                          $.each(data, function(i, item) {
  45:                              $(‘#Orders‘).append($(‘<option></option>‘).val(item.Key).text(item.Value));
  46:                          });
  47:                      }
  48:                  }
  49:              });
  50:          }
  51:   
  52:      </script>
  53:  }
  54:   

 

  选择订单Select,显示产品Select

□ 服务层方法

   1:          //根据订单获取产品,订单和产品之间有中间表订单明细
   2:          public static List<Product> GetProductsByOrder(int orderID)
   3:          {
   4:              List<Product> products = new List<Product>();
   5:              products.Add(new Product(){ProductID = 1, Name = "产品1", UnitPrice = 85m});
   6:              products.Add(new Product() { ProductID = 2, Name = "产品2", UnitPrice = 95m });
   7:              products.Add(new Product() { ProductID = 3, Name = "产品3", UnitPrice = 65m });
   8:              products.Add(new Product() { ProductID = 4, Name = "产品4", UnitPrice = 75m });
   9:   
  10:              List<OrderDetail> orderDetails = new List<OrderDetail>();
  11:              orderDetails.Add(new OrderDetail(){OrderDetailID = 1, OrderID = 1, Products = new List<Product>()
  12:              {
  13:                  products[0],
  14:                  products[1]
  15:              }});
  16:   
  17:              orderDetails.Add(new OrderDetail()
  18:              {
  19:                  OrderDetailID = 2,
  20:                  OrderID = 2,
  21:                  Products = new List<Product>()
  22:              {
  23:                  products[2],
  24:                  products[3]
  25:              }
  26:              });
  27:   
  28:              orderDetails.Add(new OrderDetail()
  29:              {
  30:                  OrderDetailID = 3,
  31:                  OrderID = 3,
  32:                  Products = new List<Product>()
  33:              {
  34:                  products[1],
  35:                  products[3]
  36:              }
  37:              });
  38:   
  39:              orderDetails.Add(new OrderDetail()
  40:              {
  41:                  OrderDetailID = 4,
  42:                  OrderID = 4,
  43:                  Products = new List<Product>()
  44:              {
  45:                  products[0],
  46:                  products[2]
  47:              }
  48:              });
  49:   
  50:              OrderDetail orderDetailsTemp = orderDetails.Where(od => od.OrderID == orderID).FirstOrDefault();
  51:              return orderDetailsTemp.Products;
  52:          }
  53:   

 

□ 控制器方法

   1:          //根据订单获取产品
   2:          [HttpPost]
   3:          public JsonResult Products(string orderID)
   4:          {
   5:              List<KeyValuePair<string,string>> items = new List<KeyValuePair<string, string>>();
   6:              int id = 0; //需要传入服务层方法的id
   7:              if (!string.IsNullOrEmpty(orderID) && int.TryParse(orderID, out id))
   8:              {
   9:                  var products = Service.GetProductsByOrder(id);
  10:                  if (products.Count() > 0)
  11:                  {
  12:                      foreach (Product product in products)
  13:                      {
  14:                          items.Add(new KeyValuePair<string, string>(
  15:                              product.ProductID.ToString(),
  16:                              product.Name
  17:                          ));
  18:                      }
  19:                  }
  20:              }
  21:              return Json(items);
  22:          }

 

□ 视图  

   1:      <p>
   2:          客户:@Html.DropDownList("Customers", (List<SelectListItem>)ViewData["c"],"==选择客户==",new {id = "Customers"} )
   3:      </p>
   4:      <p>
   5:          订单:<select id="Orders" name="Orders">
   6:                 <option value="">==选择订单==</option>
   7:             </select> 
   8:      </p>
   9:      <p>
  10:          产品:<select id="Products" name="Products">
  11:                 <option value="">==选择产品==</option>
  12:             </select>
  13:      </p>

 

□ 视图js部分

   1:  @section scripts
   2:  {
   3:      <script type="text/javascript">
   4:          $(function () {
   5:   
   6:              //初始化
   7:              init();
   8:   
   9:              //点击客户触发
  10:              $(‘#Customers‘).change(function() {               
  11:                  changeCustomer();
  12:              });
  13:   
  14:              //点击订单触发
  15:              $(‘#Orders‘).change(function() {
  16:                  changeOrder();
  17:              });
  18:          });
  19:   
  20:          //初始化
  21:          function init() {
  22:              $(‘#ButtonSubmit‘).hide();
  23:              $(‘#Orders‘).attr("disabled", "true");
  24:              $(‘#Products‘).attr("disabled", "true");
  25:          }
  26:   
  27:          //点击客户事件
  28:          function changeCustomer() {
  29:              var selectedValue = $(‘#Customers option:selected‘).val();
  30:              if ($.trim(selectedValue).length > 0) {
  31:                  getOrders(selectedValue);
  32:              }
  33:          }
  34:   
  35:          //点击客户显示订单
  36:          function getOrders(customerID) {
  37:              $.ajax({
  38:                  url: ‘@Url.Action("Orders","Home")‘,
  39:                  data: { customerID: customerID },
  40:                  type: ‘post‘,
  41:                  cache: false,
  42:                  async: false,
  43:                  dataType: ‘json‘,
  44:                  success: function(data) {
  45:                      if (data.length > 0) {
  46:                          $(‘#Orders‘).removeAttr("disabled");
  47:                          $(‘#Orders‘).empty();
  48:                          $(‘#Orders‘).append($(‘<option></option>‘).val(‘‘).text(‘==选择订单==‘));
  49:                          $.each(data, function(i, item) {
  50:                              $(‘#Orders‘).append($(‘<option></option>‘).val(item.Key).text(item.Value));
  51:                          });
  52:                      }
  53:                  }
  54:              });
  55:          }
  56:   
  57:          //点击订单事件
  58:          function changeOrder() {
  59:              var selectedValue = $(‘#Orders option:selected‘).val();
  60:              if ($.trim(selectedValue).length > 0) {
  61:                  getProducts(selectedValue);
  62:              }
  63:          }
  64:   
  65:          //点击订单显示产品
  66:          function getProducts(orderID) {
  67:              $.ajax({
  68:                  url: ‘@Url.Action("Products","Home")‘,
  69:                  data: { orderID: orderID },
  70:                  type: ‘post‘,
  71:                  cache: false,
  72:                  async: false,
  73:                  dataType: ‘json‘,
  74:                  success: function(data) {
  75:                      if (data.length > 0) {
  76:                          $(‘#Products‘).removeAttr("disabled");
  77:                          $(‘#Products‘).empty();               
  78:                          $(‘#Products‘).append($(‘<option></option>‘).val(‘‘).text(‘==选择产品==‘));
  79:                          $.each(data, function(i, item) {
  80:                              $(‘#Products‘).append($(‘<option></option>‘).val(item.Key).text(item.Value));
  81:                          });
  82:                      }
  83:                  }
  84:              });
  85:          }
  86:      </script>
  87:  }
  88:   

 

  选择产品Select项,点击"显示产品信息"按钮,显示产品信息

□ 服务层方法

   1:          //根据产品ID获得产品信息
   2:          public static Product GetProduct(int productId)
   3:          {
   4:              List<Product> products = new List<Product>();
   5:              products.Add(new Product() { ProductID = 1, Name = "产品1", UnitPrice = 85m });
   6:              products.Add(new Product() { ProductID = 2, Name = "产品2", UnitPrice = 95m });
   7:              products.Add(new Product() { ProductID = 3, Name = "产品3", UnitPrice = 65m });
   8:              products.Add(new Product() { ProductID = 4, Name = "产品4", UnitPrice = 75m });
   9:   
  10:              return products.Where(p => p.ProductID == productId).FirstOrDefault();
  11:          }

 

□ 控制器方法

   1:          //根据产品ID获得产品
   2:          public ActionResult ProductInfo(string productID)
   3:          {
   4:              int id = 0;
   5:              if (!string.IsNullOrEmpty(productID) && int.TryParse(productID, out id))
   6:              {
   7:                  var product = Service.GetProduct(id);
   8:                  ViewData.Model = product;
   9:              }
  10:              return PartialView("_ProductInfo");
  11:          }

 

□ _ProductInfo部分视图

   1:  @model MvcApplication2.Models.Product
   2:   
   3:  <fieldset>
   4:      <legend>Product</legend>
   5:   
   6:      <div class="display-label">
   7:           @Html.DisplayNameFor(model => model.Name)
   8:      </div>
   9:      <div class="display-field">
  10:          @Html.DisplayFor(model => model.Name)
  11:      </div>
  12:   
  13:      <div class="display-label">
  14:           @Html.DisplayNameFor(model => model.UnitPrice)
  15:      </div>
  16:      <div class="display-field">
  17:          @Html.DisplayFor(model => model.UnitPrice)
  18:      </div>
  19:  </fieldset>
  20:   

 

□ 视图

   1:  <div id="wrapper">
   2:      <p>
   3:          客户:@Html.DropDownList("Customers", (List<SelectListItem>)ViewData["c"],"==选择客户==",new {id = "Customers"} )
   4:      </p>
   5:      <p>
   6:          订单:<select id="Orders" name="Orders">
   7:                 <option value="">==选择订单==</option>
   8:             </select> 
   9:      </p>
  10:      <p>
  11:          产品:<select id="Products" name="Products">
  12:                 <option value="">==选择产品==</option>
  13:             </select>
  14:      </p>
  15:      <p>
  16:          <input  type ="button"  id ="ButtonReset"  value ="清空"  />
  17:          <input type ="button"  id ="ButtonSubmit"  value ="显示产品信息"  />
  18:   
  19:      </p>
  20:  </div>
  21:   

 

□ 视图js部分

   1:  @section scripts
   2:  {
   3:      <script type="text/javascript">
   4:          $(function () {
   5:   
   6:              //初始化
   7:              init();
   8:   
   9:              //点击客户触发
  10:              $(‘#Customers‘).change(function() {               
  11:                  changeCustomer();
  12:              });
  13:   
  14:              //点击订单触发
  15:              $(‘#Orders‘).change(function() {
  16:                  changeOrder();
  17:              });
  18:   
  19:              //点击产品显示按钮
  20:              $(‘#Products‘).change(function() {
  21:                  changeProuct();
  22:              });
  23:   
  24:              //点击显示产品
  25:              $(‘#ButtonSubmit‘).click(function() {
  26:                  displayProductById();
  27:              });
  28:   
  29:              //清空按钮
  30:              $(‘#ButtonReset‘).click(function() {
  31:                  resetContent();
  32:              });
  33:          });
  34:   
  35:          //初始化
  36:          function init() {
  37:              $(‘#ButtonSubmit‘).hide();
  38:              $(‘#Orders‘).attr("disabled", "true");
  39:              $(‘#Products‘).attr("disabled", "true");
  40:          }
  41:   
  42:          //点击客户事件
  43:          function changeCustomer() {
  44:              var selectedValue = $(‘#Customers option:selected‘).val();
  45:              if ($.trim(selectedValue).length > 0) {
  46:                  getOrders(selectedValue);
  47:              }
  48:          }
  49:   
  50:          //点击客户显示订单
  51:          function getOrders(customerID) {
  52:              $.ajax({
  53:                  url: ‘@Url.Action("Orders","Home")‘,
  54:                  data: { customerID: customerID },
  55:                  type: ‘post‘,
  56:                  cache: false,
  57:                  async: false,
  58:                  dataType: ‘json‘,
  59:                  success: function(data) {
  60:                      if (data.length > 0) {
  61:                          $(‘#Orders‘).removeAttr("disabled");
  62:                          $(‘#Orders‘).empty();
  63:                          $(‘#Orders‘).append($(‘<option></option>‘).val(‘‘).text(‘==选择订单==‘));
  64:                          $.each(data, function(i, item) {
  65:                              $(‘#Orders‘).append($(‘<option></option>‘).val(item.Key).text(item.Value));
  66:                          });
  67:                      }
  68:                  }
  69:              });
  70:          }
  71:   
  72:          //点击订单事件
  73:          function changeOrder() {
  74:              var selectedValue = $(‘#Orders option:selected‘).val();
  75:              if ($.trim(selectedValue).length > 0) {
  76:                  getProducts(selectedValue);
  77:              }
  78:          }
  79:   
  80:          //点击订单显示产品
  81:          function getProducts(orderID) {
  82:              $.ajax({
  83:                  url: ‘@Url.Action("Products","Home")‘,
  84:                  data: { orderID: orderID },
  85:                  type: ‘post‘,
  86:                  cache: false,
  87:                  async: false,
  88:                  dataType: ‘json‘,
  89:                  success: function(data) {
  90:                      if (data.length > 0) {
  91:                          $(‘#Products‘).removeAttr("disabled");
  92:                          $(‘#Products‘).empty();               
  93:                          $(‘#Products‘).append($(‘<option></option>‘).val(‘‘).text(‘==选择产品==‘));
  94:                          $.each(data, function(i, item) {
  95:                              $(‘#Products‘).append($(‘<option></option>‘).val(item.Key).text(item.Value));
  96:                          });
  97:                      }
  98:                  }
  99:              });
 100:          }
 101:   
 102:          //根据产品ID获取产品信息
 103:          function displayProductById() {
 104:              var selectedValue = $(‘#Products option:selected‘).val();
 105:              if ($.trim(selectedValue).length > 0) {
 106:                  $.ajax({
 107:                      url: ‘@Url.Action("ProductInfo","Home")‘,
 108:                      data: { productID: selectedValue },
 109:                      type: ‘post‘,
 110:                      cache: false,
 111:                      async: false,
 112:                      dataType: ‘html‘,
 113:                      success: function(data) {
 114:                          if (data.length > 0) {
 115:                              $(‘#ProductInfo‘).empty();
 116:                              $(‘#ProductInfo‘).html(data);
 117:                          }
 118:                      }
 119:                  });
 120:              }
 121:          }
 122:   
 123:          //点击产品显示按钮
 124:          function changeProuct() {
 125:              var selectedValue = $(‘#Products option:selected‘).val();
 126:              if ($.trim(selectedValue).length > 0) {
 127:                  $(‘#ButtonSubmit‘).show();
 128:              } else {
 129:                  $(‘#ButtonSubmit‘).hide();
 130:                  $(‘#Products‘).empty();
 131:              }
 132:          }
 133:   
 134:          //点击清空按钮
 135:          function resetContent() {
 136:              $(‘#Customers option:eq(0)‘).attr(‘selected‘, true);
 137:   
 138:              //订单Select,禁用,清空并显示第一项        
 139:              $(‘#Orders‘).attr("disabled", "true");
 140:              $(‘#Orders‘).empty();
 141:              $(‘#Orders‘).append($(‘<option></option>‘).val(‘‘).text(‘==选择订单==‘));
 142:   
 143:              //产品Select,禁用,清空并显示第一项   
 144:              $(‘#Products‘).attr("disabled", "true");
 145:              $(‘#Products‘).empty();
 146:              $(‘#Products‘).append($(‘<option></option>‘).val(‘‘).text(‘==选择产品==‘));
 147:   
 148:              $(‘#ButtonSubmit‘).hide();
 149:              $(‘#ProductInfo‘).empty();
 150:          }
 151:      </script>
 152:  }
 153:   

 

关于本篇的部分源码:下载

 

参考资料:
Kevin Tseng

MVC三级联动无刷新,布布扣,bubuko.com

MVC三级联动无刷新

上一篇:Linux数据备份与恢复


下一篇:Linux下文件分析 | 命令行