15

Im new to ASP.NET MVC and want to do a simple page that retrieves some data using Entity and displays it in a paging datagrid.

Can anyone point me in the right direction or to a tutorial etc.

Its just a proof of concept for retrieving a list of stuff and displaying it.

Sampath
  • 63,341
  • 64
  • 307
  • 441
Dale Fraser
  • 4,623
  • 7
  • 39
  • 76
  • 3
    I've done that, can't find a simple datagrid example with MVC 4, razor views etc, there are lots of old examples, but I want something new. But if your google skills are better than mine, feel free to share. – Dale Fraser Dec 29 '12 at 10:45

2 Answers2

23

For that you can use ASP.NET MVC jqGrid.

Below I have mentioned sample code for how to achieve that.

Sample Image

enter image description here

Action Method

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 Set up

<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>

You can get more details from GridView in ASP.NET MVC Here

OR

Check This Get the Most out of WebGrid in ASP.NET MVC (compatible with MVC 4)

I hope this will help to you.

Sampath
  • 63,341
  • 64
  • 307
  • 441
  • How about some indentation? – Robert Harvey Dec 29 '12 at 07:53
  • @RobertHarvey Yes. Actually formatting is the very annoying thing with SOF Editor.So, can't you suggest SOF to give us a better Editor ?.Any way I did it.I feel now it looks good.Check that. – Sampath Dec 29 '12 at 08:11
  • Was looking for an MVC 4 example, razor views etc. – Dale Fraser Dec 29 '12 at 10:44
  • @DaleFraser yes you can apply this for mvc 4 razor views also.This does not depends on the mvc version.You can apply it for any version. Pure jquery. This jqGrid having lot of features.So you can customize it according to your situation very easily.I have mentioned a link also for more information.source code also there.Try it.If you having any problem please let me know. – Sampath Dec 29 '12 at 11:18
  • @DaleFraser when we consider MVC development this is the best practice for handling things on client side.It's not like classical web forms.There having lot of server side controls.But MVC it's different.So try to do things in client side by using jquery as a client side library. – Sampath Dec 29 '12 at 11:24
  • @DaleFraser I have updated another link on my post.Check that.http://social.msdn.microsoft.com/Forums/ta/csharpgeneral/thread/cc08073d-caf1-4f66-af3d-148b51a63840 – Sampath Dec 29 '12 at 15:46
  • In the demo, `#list` is `
    `.
    – NibblyPig Jan 24 '14 at 12:58
  • nice example. there are so many client side tools available now. developers are drifting away from server side tools. – JoshYates1980 Dec 01 '14 at 20:39
  • 1
    @a.boussema Check this : http://stackoverflow.com/questions/13506179/is-jqgrid-asp-net-mvc-version-free – Sampath Aug 02 '15 at 09:39
  • @Sampath what `#pager` should be? – Mr. Robot Nov 19 '15 at 21:13
  • @IamnotBatman You can see that if you download the project by using above mentioned url.Please go ahead and do that. – Sampath Nov 20 '15 at 07:32
6
  1. ASP.net MVC Awesome - jQuery Ajax helpers (demo) ASP.net MVC Awesome grid
  2. jqxGrid jqxGrid
  3. Grid.MVC (codeplex) sorting, paging, filtering Grid.MVC demo
  4. MVCContrib.Grid
  5. jqGrid (demo) jqGrid
  6. FuelUX repeater fuelux repeater demo
  7. IgniteUI Grid IgniteUI Grid
SMUsamaShah
  • 7,677
  • 22
  • 88
  • 131