Sunday 14 July 2013

JQGrid Helper Class ASP.NET MVC


Today i will show tutorial how to create GridView(asp.net) using MVCJQGrid in asp.net MVC ..

First step is to install MVCJQGrid in your project application(MVC). In This tutorial i will show you how to install MVCJQGrid using NuGet in Microsoft Visual Studio 2010.


Install MVCJQGrid

1. In VS2010 open NuGet Manager.


2. Search MVCJQGrid and install the latest MVCJQGrid from NuGet Package Manager.


Note : Recommended install latest version of JQGrid
3. Apply Installed NuGet Package into your project.
Ok done the first step. Now your project already have MVCJQGrid package with it.


Create your first Data Grid using MVCJQGrid

First of all in order for you to start write MVCJQGrid coding, you need to add new namespace for the project. In This tutorial i will add the MvcJQGrid in web.config file :

Web.Config File
 <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
        <add namespace="MvcSiteMapProvider.Web.Html" />
        <add namespace="MvcJqGrid" />
      </namespaces>
    </pages>

 

Lets Start Coding

If you using BundleConfig class to add bundle of javascript file to your share layout view , configure your BundleConfig class to include jQGrid script file and the css style :

BundleConfig 
   bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js",
                            "~/Scripts/i18n/grid.locale-en.js",
                             "~/Scripts/jquery.jqGrid.js",
                             "~/Scripts/jquery-ui-1.10.0.js"
                            ));
    bundles.Add(new StyleBundle("~/Content/css").Include(
                    "~/Content/site.css",
                    "~/Content/jquery.jqGrid/ui.jqgrid.css"                  
                    ));

Or just add file jquery.jqGrid.js,jquery-ui-1.10.0.js and css style ui.jqgrid.css  using old style method :
    <script type="text/javascript" src="jquery.jqGrid.js"></script>
    <script type="text/javascript" src="jquery-ui-1.10.0.js"></script>
    <link href="ui.jqgrid.css" type="text/css" rel="Stylesheet" />
Lets add coding MVCJQGrid for your first data grid in MVC. Add code below in your view to create data grid in your view

View

@using MvcJqGrid

     @{
                MvcJqGrid.DataReaders.JsonReader jsonReader = new MvcJqGrid.DataReaders.JsonReader();
                jsonReader.RepeatItems = false;
                jsonReader.Id = "dataJson";
            }
            @(Html.Grid("GridDataBasic")
                .SetCaption("List Of User")
                .AddColumn(new Column("AdminID"))
                .AddColumn(new Column("Email"))
                .AddColumn(new Column("Tel"))
                .AddColumn(new Column("Role"))
                .AddColumn(new Column("Active"))
                .SetUrl("/Home/GridDataBasic")
                .SetAutoEncode(true)
                .SetDataType(MvcJqGrid.Enums.DataType.Json)
                .SetAutoWidth(false)
                .SetWidth(650)
                .SetRowNum(10)
                .SetJsonReader(jsonReader)
                .SetLoadUi(MvcJqGrid.Enums.LoadUi.Block)
                .SetRowList(new int[] { 10, 15, 20, 50 })
                .SetViewRecords(true)
                .SetGridView(true)
                .SetEmptyRecords("No record Found")
                .SetShowAllSortIcons(true)
                .SetShrinkToFit(true)               
                .SetPager("pager"))
Ok now create method in controller to handle request fromView. This method will handle every request from View and will pass JSON result to View

Controller
public ActionResult GridDataBasic(GridSettings grid)
        {
            IRepositoryUser _repository = new IRepositoryUser();
            var query = _repository.Users();

            //sorting
            query = query.OrderBy<User>(grid.SortColumn, grid.SortOrder);

            //count
            var count = query.Count();

            //paging
            var data = query.Skip((grid.PageIndex - 1) * grid.PageSize).Take(grid.PageSize).ToArray();

            var result = new
            {
                total = (int)Math.Ceiling((double)count / grid.PageSize),
                page = grid.PageIndex,
                records = count,
                rows = (from UserInfo in data
                        select new
                        {
                            AdminID = UserInfo.AdminID.ToString(),
                            Email = UserInfo.Email,
                            NoTel = UserInfo.Tel,
                            Role = UserInfo.Role,
                            Active = UserInfo.Active,
                        }).ToArray()
            };

            return Json(result, JsonRequestBehavior.AllowGet);
        }

When you copy code above. There will be error because you need to create Class IRepositoryUser, Class User, Class LinqExtensions, enum WhereOperation, and Class StringEnum.

So just copy and paste code below and try to understand the coding work.

Class IRepositoryUser
class IRepositoryUser
    {
        public IQueryable<User> Users()
        {
            return new List<User>()
            {
                new User { AdminID = "John", Tel="010-99002202", Role="Administrator", Email="John@gmail.com" , Active="Active"},
                new User { AdminID = "Johny", Tel="010-99002202", Role="Administrator", Email="Johny@gmail.com" , Active="Active"},
                new User { AdminID = "samuel", Tel="010-99002202", Role="Super Administrator", Email="samuel@gmail.com" , Active="Active"},
            }.AsQueryable();

        }
    } 
Class User
 public class User
    {
        public string AdminID { get; set; }
        public string Email { get; set; }
        public string Tel { get; set; }
        public string Role { get; set; }
        public string Active { get; set; }
    }
enum WhereOperation
public enum WhereOperation
    {
        [StringValue("eq")]
        Equal,
        [StringValue("ne")]
        NotEqual,
        [StringValue("cn")]
        Contains
    }  
static class LinqExtensions
public static class LinqExtensions
    {
        /// <summary>Orders the sequence by specific column and direction.</summary>
        /// <param name="query">The query.</param>
        /// <param name="sortColumn">The sort column.</param>
        /// <param name="ascending">if set to true [ascending].</param>
        public static IQueryable<T> OrderBy<T>(this IQueryable<T> query, string sortColumn, string direction)
        {
            if (sortColumn == "")
            {
                sortColumn = "AdminID";
            }

            string methodName = string.Format("OrderBy{0}",
                direction.ToLower() == "asc" ? "" : "descending");

            ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");

            MemberExpression memberAccess = null;
            foreach (var property in sortColumn.Split('.'))
                memberAccess = MemberExpression.Property
                   (memberAccess ?? (parameter as Expression), property);

            LambdaExpression orderByLambda = Expression.Lambda(memberAccess, parameter);

            MethodCallExpression result = Expression.Call(
                      typeof(Queryable),
                      methodName,
                      new[] { query.ElementType, memberAccess.Type },
                      query.Expression,
                      Expression.Quote(orderByLambda));

            return query.Provider.CreateQuery<T>(result);
        }

        public static IQueryable<T> Where<T>(this IQueryable<T> query,
            string column, object value, WhereOperation operation)
        {
            if (string.IsNullOrEmpty(column))
                return query;

            ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");

            MemberExpression memberAccess = null;
            foreach (var property in column.Split('.'))
                memberAccess = MemberExpression.Property
                   (memberAccess ?? (parameter as Expression), property);

            //change param value type
            //necessary to getting bool from string
            ConstantExpression filter = Expression.Constant
                (
                    Convert.ChangeType(value, memberAccess.Type)
                );

            //switch operation
            Expression condition = null;
            LambdaExpression lambda = null;
            switch (operation)
            {
                //equal ==
                case WhereOperation.Equal:
                    condition = Expression.Equal(memberAccess, filter);
                    lambda = Expression.Lambda(condition, parameter);
                    break;
                //not equal !=
                case WhereOperation.NotEqual:
                    condition = Expression.NotEqual(memberAccess, filter);
                    lambda = Expression.Lambda(condition, parameter);
                    break;
                //string.Contains()
                case WhereOperation.Contains:
                    condition = Expression.Call(memberAccess,
                        typeof(string).GetMethod("Contains"),
                        Expression.Constant(value));
                    lambda = Expression.Lambda(condition, parameter);
                    break;
            }
            MethodCallExpression result = Expression.Call(
                   typeof(Queryable), "Where",
                   new[] { query.ElementType },
                   query.Expression,
                   lambda);

            return query.Provider.CreateQuery<T>(result);
        }
    }
 class StringEnum
 public class StringEnum
    {
        #region Instance implementation

        private Type _enumType;
        private static Hashtable _stringValues = new Hashtable();

        /// <summary>
        /// Creates a new <see cref="StringEnum"/> instance.
        /// </summary>
        /// <param name="enumType">Enum type.</param>
        public StringEnum(Type enumType)
        {
            if (!enumType.IsEnum)
                throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", enumType.ToString()));

            _enumType = enumType;
        }

        /// <summary>
        /// Gets the string value associated with the given enum value.
        /// </summary>
        /// <param name="valueName">Name of the enum value.</param>
        /// <returns>String Value</returns>
        public string GetStringValue(string valueName)
        {
            Enum enumType;
            string stringValue = null;
            try
            {
                enumType = (Enum)Enum.Parse(_enumType, valueName);
                stringValue = GetStringValue(enumType);
            }
            catch (Exception) { }//Swallow!

            return stringValue;
        }

        /// <summary>
        /// Gets the string values associated with the enum.
        /// </summary>
        /// <returns>String value array</returns>
        public Array GetStringValues()
        {
            ArrayList values = new ArrayList();
            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in _enumType.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                    values.Add(attrs[0].Value);

            }

            return values.ToArray();
        }

        /// <summary>
        /// Gets the values as a 'bindable' list datasource.
        /// </summary>
        /// <returns>IList for data binding</returns>
        public IList GetListValues()
        {
            Type underlyingType = Enum.GetUnderlyingType(_enumType);
            ArrayList values = new ArrayList();
            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in _enumType.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                    values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType), attrs[0].Value));

            }

            return values;

        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <returns>Existence of the string value</returns>
        public bool IsStringDefined(string stringValue)
        {
            return Parse(_enumType, stringValue) != null;
        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
        /// <returns>Existence of the string value</returns>
        public bool IsStringDefined(string stringValue, bool ignoreCase)
        {
            return Parse(_enumType, stringValue, ignoreCase) != null;
        }

        /// <summary>
        /// Gets the underlying enum type for this instance.
        /// </summary>
        /// <value></value>
        public Type EnumType
        {
            get { return _enumType; }
        }

        #endregion

        #region Static implementation

        /// <summary>
        /// Gets a string value for a particular enum value.
        /// </summary>
        /// <param name="value">Value.</param>
        /// <returns>String Value associated via a <see cref="StringValueAttribute"/> attribute, or null if not found.</returns>
        public static string GetStringValue(Enum value)
        {
            string output = null;
            Type type = value.GetType();

            if (_stringValues.ContainsKey(value))
                output = (_stringValues[value] as StringValueAttribute).Value;
            else
            {
                //Look for our 'StringValueAttribute' in the field's custom attributes
                FieldInfo fi = type.GetField(value.ToString());
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                {
                    _stringValues.Add(value, attrs[0]);
                    output = attrs[0].Value;
                }

            }
            return output;

        }

        /// <summary>
        /// Parses the supplied enum and string value to find an associated enum value (case sensitive).
        /// </summary>
        /// <param name="type">Type.</param>
        /// <param name="stringValue">String value.</param>
        /// <returns>Enum value associated with the string value, or null if not found.</returns>
        public static object Parse(Type type, string stringValue)
        {
            return Parse(type, stringValue, false);
        }

        /// <summary>
        /// Parses the supplied enum and string value to find an associated enum value.
        /// </summary>
        /// <param name="type">Type.</param>
        /// <param name="stringValue">String value.</param>
        /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
        /// <returns>Enum value associated with the string value, or null if not found.</returns>
        public static object Parse(Type type, string stringValue, bool ignoreCase)
        {
            object output = null;
            string enumStringValue = null;

            if (!type.IsEnum)
                throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", type.ToString()));

            //Look for our string value associated with fields in this enum
            foreach (FieldInfo fi in type.GetFields())
            {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                    enumStringValue = attrs[0].Value;

                //Check for equality then select actual enum value.
                if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)
                {
                    output = Enum.Parse(type, fi.Name);
                    break;
                }
            }

            return output;
        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <param name="enumType">Type of enum</param>
        /// <returns>Existence of the string value</returns>
        public static bool IsStringDefined(Type enumType, string stringValue)
        {
            return Parse(enumType, stringValue) != null;
        }

        /// <summary>
        /// Return the existence of the given string value within the enum.
        /// </summary>
        /// <param name="stringValue">String value.</param>
        /// <param name="enumType">Type of enum</param>
        /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
        /// <returns>Existence of the string value</returns>
        public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase)
        {
            return Parse(enumType, stringValue, ignoreCase) != null;
        }

        #endregion
    }
class StringValueAttribute : Attribute
public class StringValueAttribute : Attribute
    {
        private string _value;

        /// <summary>
        /// Creates a new <see cref="StringValueAttribute"/> instance.
        /// </summary>
        /// <param name="value">Value.</param>
        public StringValueAttribute(string value)
        {
            _value = value;
        }

        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <value></value>
        public string Value
        {
            get { return _value; }
        }
    }


Output


No comments :