[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1021
  • Last Modified:

adding column sorting to flexigrid in ASP.NET mvc

Hi experts,

I saw this Flexigrid example for using it with ASP.NET MVC.

http://www.ienablemuch.com/2011/03/using-flexigrid-for-aspnet-mvc.html

In this example they are using no sqlite as their database.

I'm using sql server 2008. So I simply changed the connection string in the web.config to this and it works fine with sql server.

<add name="EntContext" connectionString="Data Source=MYServer\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient" />

In this example they are using the Code First Entity Framework.

This example uses the Customer table from the Northwind database.

I'm using Visual Studio 2013 and I created a ASP.NET MVC 4 project using the Basic Template, C# and Aspx view engine.

My Project Directory looks like this:

my directory
Here is the code I have, which is exactly the same as listed at the web link above.

Helper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FlexigridUsingMvc2.Extensions
{
    public static class Helpers
    {
        public static IQueryable<T> LimitAndOffset<T>(this IQueryable<T> q,
                            int pageSize, int pageOffset)
        {
            return q.Skip((pageOffset - 1) * pageSize).Take(pageSize);
        }
    }

}

[subtitle]Models[/subtitle]

[b]All.css[/b]

[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace FlexigridUsingMvc2.Models
{
    public class Customer
    {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
    }
    
    public class EntContext : DbContext
    {
        public DbSet<Customer> Customers { get; set; }
    }
}

Open in new window


Controller


HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FlexigridUsingMvc2.Models;
using FlexigridUsingMvc2.Extensions;

namespace FlexigridUsingMvc2.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        
        [HttpPost]
        public JsonResult List(int page, int rp, string qtype, string letter_pressed, string query)
        {

            using (var db = new EntContext())
            {
                if (letter_pressed == "ALL") letter_pressed = "";

                Func<IQueryable<Customer>> CustomerFiltered = () =>
                    db.Customers
                    .Where(x =>
                            (
                                (
                                    !string.IsNullOrEmpty(letter_pressed)
                                    && x.CompanyName.StartsWith(letter_pressed)
                                )
                                ||
                                string.IsNullOrEmpty(letter_pressed)
                            )
                            &&
                            (
                                (
                                    !string.IsNullOrEmpty(query)
                                    &&
                                    (
                                        (qtype == "CompanyName" && x.CompanyName.Contains(query))
                                        ||
                                        (qtype == "ContactName" && x.ContactName.Contains(query))
                                        ||
                                        (qtype == "ContactTitle" && x.ContactTitle.Contains(query))
                                    )
                                )
                                ||
                                string.IsNullOrEmpty(query)
                            )
                        );
                
                return Json(
                    new
                    {
                        page = page,
                        total = CustomerFiltered().Count(),
                        rows =
                            CustomerFiltered()
                            .OrderBy(x => x.CompanyName)
                            .LimitAndOffset(pageSize: rp, pageOffset: page)
                            .ToList()
                            .Select(x =>
                                new
                                {
                                    id = x.CustomerID,
                                    cell = new string[] { x.CompanyName, x.ContactName, x.ContactTitle }
                                })
                    });


            }//using
        }//List

        public ActionResult Index()
        {
            return View();
        }

    }
}

Open in new window


Views


Home/Index.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
    <link href="<%: Url.Content("~/Content/Site.css")%>" rel="stylesheet" type="text/css" />
    <script src="<%: Url.Content("~/Scripts/jquery-1.8.2.min.js")%>" type="text/javascript"></script>
    <script src="<%: Url.Content("/Scripts/flexigrid/flexigrid.pack.js")%>" type="text/javascript"></script>
    <link href="<%: Url.Content("~/Scripts/flexigrid/css/flexigrid.css")%>" rel="stylesheet" type="text/css" />
    
    <script type="text/javascript">
        $(document).ready(function () {     
            
            $("#fff").flexigrid
            (
            {
                url: '/Home/List/',
                dataType: 'json',
                colModel: [                
                { display: 'Company', name: 'CompanyName', width: 200, sortable: true, align: 'left' },
                { display: 'Contact', name: 'ContactName', width: 280, sortable: true, align: 'left' },
                { display: 'Contact Title', name: 'ContactTitle', width: 220, sortable: true, align: 'left' }
                ],
                buttons: [
                { name: 'Add', bclass: 'add', onpress: add },
                { name: 'Edit', bclass: 'edit', onpress: edit },
                { name: 'Delete', bclass: 'delete', onpress: del },                                                
                { separator: true },
                { name: 'A', onpress: sortAlpha },
                { name: 'B', onpress: sortAlpha },
                { name: 'C', onpress: sortAlpha },
                { name: 'D', onpress: sortAlpha },
                { name: 'E', onpress: sortAlpha },
                { name: 'F', onpress: sortAlpha },
                { name: 'G', onpress: sortAlpha },
                { name: 'H', onpress: sortAlpha },
                { name: 'I', onpress: sortAlpha },
                { name: 'J', onpress: sortAlpha },
                { name: 'K', onpress: sortAlpha },
                { name: 'L', onpress: sortAlpha },
                { name: 'M', onpress: sortAlpha },
                { name: 'N', onpress: sortAlpha },
                { name: 'O', onpress: sortAlpha },
                { name: 'P', onpress: sortAlpha },
                { name: 'Q', onpress: sortAlpha },
                { name: 'R', onpress: sortAlpha },
                { name: 'S', onpress: sortAlpha },
                { name: 'T', onpress: sortAlpha },
                { name: 'U', onpress: sortAlpha },
                { name: 'V', onpress: sortAlpha },
                { name: 'W', onpress: sortAlpha },
                { name: 'X', onpress: sortAlpha },
                { name: 'Y', onpress: sortAlpha },
                { name: 'Z', onpress: sortAlpha },
                { name: 'ALL', onpress: sortAlpha }
                ],
                searchitems: [
                { display: 'Company', name: 'CompanyName', isdefault: true },
                { display: 'Contact', name: 'ContactName' },
                { display: 'Contact Title', name: 'ContactTitle' }
                ],
                singleSelect: true,
                sortname: "CompanyName",
                sortorder: "asc",
                usepager: true,
                title: 'Companies',
                useRp: true,
                rp: 10,
                showTableToggleBtn: false,
                width: 800,
                height: 255
            }
            );

        });

        function sortAlpha(com) {
            jQuery('#fff').flexOptions({ newp: 1, params: [{ name: 'letter_pressed', value: com }, { name: 'qtype', value: $('select[name=qtype]').val()}] });
            jQuery("#fff").flexReload();
        }
        
        function edit(com, grid) {

            // alert(com); // Edit
            
            if ( $('.trSelected',grid).length == 1 ) 
            {
                var items = $('.trSelected',grid);
                alert(com + ' ' + items[0].id.substr(3));
            }
        }
        
        function add(com, grid) {

            alert(com); 

            /*if ($('.trSelected', grid).length == 1) {
                var items = $('.trSelected', grid);
                alert(items[0].id.substr(3));
            }*/
        }
        
        function del(com, grid) {

            // alert(com); // Delete

            if ($('.trSelected', grid).length == 1) {
                var items = $('.trSelected', grid);
                alert(com + ' ' + items[0].id.substr(3));
            }
        }
        
    </script>
    
    <title>Flexigrid example showing Customers table data</title>
    
</head>
<body>
    <div>
        <table id="fff" style="display:none"></table>
    </div>
</body>




</html>

Open in new window



When I run my application i get this:

my flexigrid working just fine
My flexigrid works fine.

If I click on the magnifying glass on the bottom toolbar I can filter just fine.
If I click on one of the letters on the top toolbar the CompanyName column is filtered by that letter. So if I click on the letter C then it filters so I only see CompanyName items that start with the letter C.

The only functionality that this flexigrid example does not have is, if I click the column header, it does not sort Ascending or Descending on that column.

Anyone know how I can add column sorting on my grid when I click on the column headers?

In my view page called Index.aspx in the flexigrid javascript in this snippet I set the sortable property for the columns to true but that didn't seem to fix it.

                colModel: [                
                { display: 'Company', name: 'CompanyName', width: 200, sortable: true, align: 'left' },
                { display: 'Contact', name: 'ContactName', width: 280, sortable: true, align: 'left' },
                { display: 'Contact Title', name: 'ContactTitle', width: 220, sortable: true, align: 'left' }
                ],

Do I have to create a javascript function to add column sorting at the bottom of my index.aspx?
or
Do I have to create a C# method in my Helper.cs file?
or
Does anyone know what I need to do to add column sorting?
dir.jpg
0
maqskywalker
Asked:
maqskywalker
1 Solution
 
Sammy AgeilCommented:
Your action has to perform the sorting.
See ActionResult FlexigridList () in this demo http://www.codeproject.com/Articles/30588/ASP-NET-MVC-Flexigrid-sample
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now