ASP.NET MVC with select2

CONTROLLER
   1:       public JsonResult GetSupplier(string keyword)
   2:          {
   3:              var data = (from s in DataContext.Supplier
   4:                          join st in DataContext.SupplierType on s.SupplierTypeId equals st.Id
   5:                          select new { supplierId = s.Id, supplierName = s.Name + "(" + st.Name + ")" });
   6:   
   7:              return Json(
   8:                  string.IsNullOrEmpty(keyword) ?
   9:                      data.Select(c => new { id = c.supplierId, name = c.supplierName }) :
  10:                      data.Where(c => c.supplierName.StartsWith(keyword)).Select(c => new { id = c.supplierId, name = c.supplierName }), JsonRequestBehavior.AllowGet);
  11:          }
  12:   
  13:   
  14:   
  15:   
  16:          public JsonResult GetSupplierById(int supplierId)
  17:          {
  18:              var data = (from s in DataContext.Supplier
  19:                          join st in DataContext.SupplierType on s.SupplierTypeId equals st.Id
  20:                          select new { supplierId = s.Id, supplierName = s.Name + "(" + st.Name + ")" });
  21:   
  22:              return Json(data.Where(c => c.supplierId == supplierId).Select(c => new { id = c.supplierId, name = c.supplierName })
  23:                  .SingleOrDefault(), JsonRequestBehavior.AllowGet);
  24:          }

VIEW
   1:          $('#SupplierId').select2({
   2:              width: '200px',
   3:              placeholder: '--- Please Select ---',
   4:              minimumInputLength: 0,
   5:              allowClear: true,
   6:              quietMillis: 100,
   7:              ajax: {
   8:                  url: '/Product/GetSupplier',
   9:                  dataType: 'json',
  10:                  data: function(term, page) { return { keyword: term }; },
  11:                  results: function(data, page) {
  12:                      return { results: data };
  13:                  }
  14:              },
  15:              formatResult: function(item) { return ('<div class=select2-user-result>' + item.name + '</div>'); },
  16:              formatSelection: function(item) { return item.name; },
  17:              escapeMarkup: function(m) { return m; },
  18:              initSelection: function(element, callback) { $.ajax({ url: '/Product/GetSupplierById', dataType: 'json', data: { supplierId: $(element).val() } }).done(function(data) { callback(data); }); }
  19:          });

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

FancyBox not work in UpdatePanel

Convert float to int

Get QueryString from JavaScript