ASP.NET MVC 4 Datagrid

Sou novo em ASP.NET MVC e quer fazer uma página simples que recupera alguns dados usando entidade e exibe-lo em um datagrid de paging.

Qualquer um pode me apontar na direção certa ou para um tutorial etc.

É apenas uma prova de conceito para recuperar uma lista de coisas e exibi-la.

Author: Sampath, 2012-12-29

2 answers

Para isso pode usar ASP.NET MVC jqGrid .

Abaixo mencionei o código da amostra para saber como conseguir isso.

Imagem De Exemplo

enter image description here

Método De Acção

public ActionResult JsonSalesCollection(DateTime startDate, DateTime endDate,
string sidx, string sord, int page, int rows)

 {
     SalesLogic logicLayer = new SalesLogic();
     List<Sale> context;

     // If we aren't filtering by date, return this month's contributions
     if (startDate == DateTime.MinValue || endDate == DateTime.MinValue)
      {
         context = logicLayer.GetSales();
      }
     else // Filter by specified date range
      {
          context = logicLayer.GetSalesByDateRange(startDate, endDate);
      }

     // Calculate page index, total pages, etc. for jqGrid to us for paging
     int pageIndex = Convert.ToInt32(page) - 1;
     int pageSize = rows;
     int totalRecords = context.Count();
     int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

     // Order the results based on the order passed into the method
     string orderBy = string.Format("{0} {1}", sidx, sord);
     var sales = context.AsQueryable()
                  .OrderBy(orderBy) // Uses System.Linq.Dynamic library for sorting
                  .Skip(pageIndex * pageSize)
                  .Take(pageSize);

      // Format the data for the jqGrid
      var jsonData = new
       {
         total = totalPages,
         page = page,
         records = totalRecords,
         rows = (
                from s in sales
                select new
                {
                   i = s.Id,
                   cell = new string[] {
                   s.Id.ToString(),
                   s.Quantity.ToString(),
                   s.Product,
                   s.Customer,
                   s.Date.ToShortDateString(), 
                   s.Amount.ToString("c")
                }
           }).ToArray()
          };

         // Return the result in json
         return Json(jsonData);
}

JQuery configurado

<script type="text/javascript">
var gridDataUrl = '/Home/JsonSalesCollection';
// use date.js to calculate the values for this month
var startDate = Date.parse('today').moveToFirstDayOfMonth();
var endDate = Date.parse('today');

jQuery("#list").jqGrid({

     url: gridDataUrl + '?startDate=' + startDate.toJSONString() + '&endDate=' +        endDate.toJSONString(),
     datatype: "json",
     mtype: 'GET',
     colNames: ['Sale Id', 'Quantity', 'Product', 'Customer', 'Date', 'Amount'],
     colModel: [
                  { name: 'Id', index: 'Id', width: 50, align: 'left' },
                  { name: 'Quantity', index: 'Quantity', width: 100, align: 'left' },
                  { name: 'Product', index: 'Product', width: 100, align: 'left' },
                  { name: 'Customer', index: 'Customer', width: 100, align: 'left' },
                  { name: 'Date', index: 'Date', width: 100, align: 'left' },
                  { name: 'Amount', index: 'Amount', width: 100, align: 'right'}],
     rowNum: 20,
     rowList: [10, 20, 30],
     imgpath: gridimgpath,
     height: 'auto',
     width: '700',
     pager: jQuery('#pager'),
     sortname: 'Id',
     viewrecords: true,
     sortorder: "desc",
     caption: "Sales"
});

</script>

Você pode obter mais detalhes de Grelha em ASP.NET MVC aqui

Ou

Vê isto. Tire o máximo proveito do WebGrid em ASP.NET MVC (compatível com a MVC 4)

Espero que isto te ajude.
 23
Author: Sampath, 2012-12-29 15:45:17