灵活掌握Asp.net MVC中GridView的使用方法

本文教程为大家分享了GridView控件的使用方法和具体实现代码,供大家参考,具体内容如下

Models文件下实体类:

 public class Customer
 {
 public int Id { get; set; } 
 public string CompanyName { get; set; } 
 public string ContactTitle { get; set; }
 public string Address { get; set; }
 public string City { get; set; }  
 public string Country { get; set; }
 public string Phone { get; set; }
 public DateTime Founded { get; set; }
 }

 public class CustomersViewModel

 {
 public IQueryable Customers { get; set; }

 public PagingInfo PagingInfo { get; set; }

 public string JsonPagingInfo { get; set; }
 }

 public static class ExpresssionBuilder
 {
 private static readonly MethodInfo containsMethod = typeof(string).GetMethod("Contains");
 private static readonly MethodInfo startsWithMethod = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
 private static readonly MethodInfo endsWithMethod = typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) });


 public static Expression> GetExpression(IList filters)
 {
  if (filters.Count == 0)
  return null;

  ParameterExpression param = Expression.Parameter(typeof(T), "t");
  Expression exp = null;

  if (filters.Count == 1)
  exp = GetExpression(param, filters[0]);
  else if (filters.Count == 2)
  exp = GetExpression(param, filters[0], filters[1]);
  else
  {
  while (filters.Count > 0)
  {
   var f1 = filters[0];
   var f2 = filters[1];

   if (exp == null)
   exp = GetExpression(param, filters[0], filters[1]);
   else
   exp = Expression.AndAlso(exp, GetExpression(param, filters[0], filters[1]));

   filters.Remove(f1);
   filters.Remove(f2);

   if (filters.Count == 1)
   {
   exp = Expression.AndAlso(exp, GetExpression(param, filters[0]));
   filters.RemoveAt(0);
   }
  }
  }

  return Expression.Lambda>(exp, param);
 }

 private static Expression GetExpression(ParameterExpression param, FilterObject filter)
 {
  MemberExpression member = Expression.Property(param, filter.Column);
  //ConstantExpression constant = Expression.Constant(filter.Value);

  //新的逻辑来处理可空Decimal和DateTime值
  UnaryExpression constant = null;
  if (member.Type == typeof(Decimal?))
  {
  constant = Expression.Convert(Expression.Constant(Decimal.Parse(filter.Value)) , member.Type);
  }
  else if (member.Type == typeof(DateTime?))
  {
  constant = Expression.Convert(Expression.Constant(DateTime.Parse(filter.Value)), member.Type);
  }
  else
  {
  constant = Expression.Convert(Expression.Constant(filter.Value), member.Type);
  }


  switch (filter.Operator)
  {
  case FilterOperator.Equals:
   return Expression.Equal(member, constant);

  case FilterOperator.GreaterThan:
   return Expression.GreaterThan(member, constant);

  case FilterOperator.GreaterThanOrEqual:
   return Expression.GreaterThanOrEqual(member, constant);

  case FilterOperator.LessThan:
   return Expression.LessThan(member, constant);

  case FilterOperator.LessThanOrEqual:
   return Expression.LessThanOrEqual(member, constant);

  case FilterOperator.Contains:
   return Expression.Call(member, containsMethod, constant);

  case FilterOperator.StartsWith:
   return Expression.Call(member, startsWithMethod, constant);

  case FilterOperator.EndsWith:
   return Expression.Call(member, endsWithMethod, constant);

  case FilterOperator.NotEqual:
   return Expression.Negate(Expression.Equal(member, constant));
  }

  return null;
 }

 private static BinaryExpression GetExpression (ParameterExpression param, FilterObject filter1, FilterObject filter2)
 {
  Expression bin1 = GetExpression(param, filter1);
  Expression bin2 = GetExpression(param, filter2);

  return Expression.AndAlso(bin1, bin2);
 }
 }

 public class PagingInfo
 {
 public List PageOptions { get; set; }

 public bool ShowPageOptions { get; set; }

 public int TotalItems { get; set; }
 public int ItemsPerPage { get; set; }
 public int CurrentPage { get; set; }

 public int TotalPages
 {
  get { return (int)Math.Ceiling((decimal)TotalItems / (ItemsPerPage != 0 ? ItemsPerPage : 1)); }
 }

 public SortObject Sort { get; set; }

 public IList Filters { get; set; }

 public string SearchTerm { get; set; }
 }

 public class SortObject
 {
 public String SortColumn { get; set; }

 public SortDirection Direction { get; set; }
 }

 public class FilterObject
 {
 public string Column { get; set; } 

 public string Value { get; set; }

 public FilterOperator Operator { get; set; }

 public FilterConjunction Conjunction { get; set; }
 }


 /********* ENUMS *************/
 public enum SortDirection
 {
 NotSet,
 Ascending,
 Descending
 }

 public enum FilterOperator
 {
 Contains,
 GreaterThan,
 GreaterThanOrEqual,
 LessThan,
 LessThanOrEqual,
 StartsWith,
 EndsWith,
 Equals,
 NotEqual
 }

 public enum FilterConjunction
 {
 And,
 Or
 }

 public class Extensions
 {
 public static string GetWhereClause(FilterObject filterObj, Type valueType)
 {  
  string whereClause = "true";
  if (valueType != typeof (DateTime))
  {
  switch (filterObj.Operator)
  {
   case FilterOperator.Contains:
   if (valueType == typeof (string))
    whereClause += string.Format(" {0} {1}.Contains(\"{2}\")", filterObj.Conjunction,
    filterObj.Column, filterObj.Value);
   break;
   case FilterOperator.GreaterThan:
   if (valueType != typeof (string))
    whereClause += string.Format(" {0} {1} > {2}", filterObj.Conjunction, filterObj.Column,
    filterObj.Value);
   break;
   case FilterOperator.GreaterThanOrEqual:
   if (valueType != typeof (string))
    whereClause += string.Format(" {0} {1} >= {2}", filterObj.Conjunction, filterObj.Column,
    filterObj.Value);
   break;
   case FilterOperator.LessThan:
   if (valueType != typeof (string))
    whereClause += string.Format(" {0} {1} < {2}", filterObj.Conjunction, filterObj.Column,
    filterObj.Value);
   break;
   case FilterOperator.LessThanOrEqual:
   if (valueType != typeof (string))
    whereClause += string.Format(" {0} {1} <= {2}", filterObj.Conjunction, filterObj.Column,
    filterObj.Value);
   break;
   case FilterOperator.StartsWith:
   if (valueType != typeof (string))
    whereClause += string.Format(" {0} {1}.StartsWith(\"{2}\")", filterObj.Conjunction,
    filterObj.Column, filterObj.Value);
   break;
   case FilterOperator.EndsWith:
   if (valueType != typeof (string))
    whereClause += string.Format(" {0} {1}.EndsWith(\"{2}\")", filterObj.Conjunction,
    filterObj.Column, filterObj.Value);
   break;
   case FilterOperator.Equals:

   whereClause +=
    string.Format(valueType == typeof (string) ? " {0} {1} == \"{2}\"" : " {0} {1} == {2}",
    filterObj.Conjunction, filterObj.Column, filterObj.Value);
   break;
   case FilterOperator.NotEqual:

   whereClause +=
    string.Format(valueType == typeof (string) ? " {0} {1} != \"{2}\"" : " {0} {1} != {2}",
    filterObj.Conjunction, filterObj.Column, filterObj.Value);
   break;
   default:
   throw new ArgumentOutOfRangeException();
  }
  }
  else
  {
  DateTime dt;
  DateTime.TryParse(filterObj.Value, out dt);

  switch (filterObj.Operator)
  {
   case FilterOperator.Contains:   
   break;
   case FilterOperator.GreaterThan:

    whereClause += string.Format(" {0} {1} > DateTime(\"{2}\")", filterObj.Conjunction, filterObj.Column, dt);
   break;
   case FilterOperator.GreaterThanOrEqual:

   whereClause += string.Format(" {0} {1} >= DateTime(\"{2}\")", filterObj.Conjunction, filterObj.Column, dt);
   break;
   case FilterOperator.LessThan:

   whereClause += string.Format(" {0} {1} < DateTime(\"{2}\")", filterObj.Conjunction, filterObj.Column, dt);
   break;
   case FilterOperator.LessThanOrEqual:
   whereClause += string.Format(" {0} {1} <= DateTime(\"{2}\")", filterObj.Conjunction, filterObj.Column, dt);
   break;
   case FilterOperator.StartsWith:   
   break;
   case FilterOperator.EndsWith:   
   break;
   case FilterOperator.Equals:
   whereClause += string.Format(" {0} {1} == DateTime(\"{2}\")", filterObj.Conjunction, filterObj.Column, dt);
   break;
   case FilterOperator.NotEqual:
   whereClause += string.Format(" {0} {1} != DateTime(\"{2}\")", filterObj.Conjunction, filterObj.Column, dt);
   break;
   default:
   throw new ArgumentOutOfRangeException();
  }
  }
  return whereClause;
 }
 }

 

 public class GridViewModelProvider
 { 
 internal static CustomersViewModel GetCustomersViewModel(MyDbContext db, PagingInfo PagingData)
 { 
  int TotalItems = 0;
  var model = new CustomersViewModel()
  {

  Customers = GetResources(db.Customers.AsQueryable(), PagingData, out TotalItems),  
  PagingInfo = new PagingInfo()
  {
   CurrentPage = PagingData.CurrentPage,
   ItemsPerPage = PagingData.ItemsPerPage,
   PageOptions = new List() { 10, 25, 50, 100 },
   ShowPageOptions = true,
   SearchTerm = PagingData.SearchTerm,
   Sort = PagingData.Sort,
   Filters = PagingData.Filters
  }  
  };

  model.PagingInfo.TotalItems = TotalItems;
  model.JsonPagingInfo = Json.Encode(model.PagingInfo);

  return model;
 }

 private static IQueryable GetResources(IQueryable Customers, PagingInfo PagingData, out int TotalItems)
 {
  var customers = Customers;

  //search
  if (!string.IsNullOrEmpty(PagingData.SearchTerm))
  {
  customers = customers.Where(x => (x.CompanyName.Contains(PagingData.SearchTerm) || x.ContactTitle.Contains(PagingData.SearchTerm)));
  }

  //filter
  if (PagingData.Filters != null)
  {  
  foreach (var filterObj in PagingData.Filters)
  {
   switch (filterObj.Column)
   {
   case "City":
    if (filterObj.Value.ToLower() != "all")
    customers = customers.Where(Extensions.GetWhereClause(filterObj, typeof(string)));
    break;

   //Add Other Filter Columns Here
   }
  }    
  }


  TotalItems = customers.Count();

  //sort
  customers = customers.OrderBy(x => x.Id);
  if (PagingData.Sort != null)
  {
  switch (PagingData.Sort.Direction)
  {
   case SortDirection.Ascending:
   if (PagingData.Sort.SortColumn == "CompanyName")
   {
    customers = customers.OrderBy(x => x.CompanyName);
   }
   else if (PagingData.Sort.SortColumn == "ContactTitle")
   {
    customers = customers.OrderBy(x => x.ContactTitle);
   }
   break;
   case SortDirection.Descending:
   if (PagingData.Sort.SortColumn == "CompanyName")
   {
    customers = customers.OrderByDescending(x => x.CompanyName);
   }
   else if (PagingData.Sort.SortColumn == "ContactTitle")
   {
    customers = customers.OrderByDescending(x => x.ContactTitle);
   }
   break;
   case SortDirection.NotSet:
   default:
   break;
  }
  }
  customers = customers
  .Skip((PagingData.CurrentPage - 1) * PagingData.ItemsPerPage).Take(PagingData.ItemsPerPage);

  return customers;
 } 
 }

 /// 
 /// 启用查询谓词的高效,动态组合。
 /// 
 public static class PredicateBuilder
 {
 /// 
 /// 创建一个计算结果为true的谓词。
 /// 
 public static Expression> True() { return param => true; }

 /// 
 /// 创建一个计算结果为false的谓词
 /// 
 public static Expression> False() { return param => false; }

 /// 
 /// 创建一个从指定的lambda表达式的谓词表达式。
 /// 
 public static Expression> Create(Expression> predicate) { return predicate; }

 /// 
 /// 结合了第二第一谓词使用逻辑“and”。
 /// 
 public static Expression> And(this Expression> first, Expression> second)
 {
  return first.Compose(second, Expression.AndAlso);
 }

 /// 
 /// 结合了第二第一谓词使用逻辑“or”。
 /// 
 public static Expression> Or(this Expression> first, Expression> second)
 {
  return first.Compose(second, Expression.OrElse);
 }

 /// 
 ///否定谓词
 /// 
 public static Expression> Not(this Expression> expression)
 {
  var negated = Expression.Not(expression.Body);
  return Expression.Lambda>(negated, expression.Parameters);
 }

 /// 
 /// 使用指定的合并函数,合并第二和第一表达式
 /// 
 static Expression Compose(this Expression first, Expression second, Func merge)
 {
  //第二参数映射到第一参数
  var map = first.Parameters
  .Select((f, i) => new { f, s = second.Parameters[i] })
  .ToDictionary(p => p.s, p => p.f);

  //第一lambda表达式的参数替换在第二lambda表达式参数
  var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);

  //从第一个表达式创建一个带参数的合并lambda表达式
  return Expression.Lambda(merge(first.Body, secondBody), first.Parameters);
 }

 class ParameterRebinder : ExpressionVisitor
 {
  readonly Dictionary map;

  ParameterRebinder(Dictionary map)
  {
  this.map = map ?? new Dictionary();
  }

  public static Expression ReplaceParameters(Dictionary map, Expression exp)
  {
  return new ParameterRebinder(map).Visit(exp);
  }

  protected override Expression VisitParameter(ParameterExpression p)
  {
  ParameterExpression replacement;

  if (map.TryGetValue(p, out replacement))
  {
   p = replacement;
  }

  return base.VisitParameter(p);
  }
 }
 }

MyDbContext.CS代码:

 public class MyDbContext : DbContext
 {
 public MyDbContext()
  : base("DefaultConnection")
 {

 }

 public DbSet Customers { get; set; }

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {  
  modelBuilder.Entity().Property(c => c.CompanyName).HasMaxLength(40);
  modelBuilder.Entity().Property(c => c.ContactTitle).HasMaxLength(40);
 }
 }

HomeController.cs控制器:

 public class HomeController : Controller
 {
 public ActionResult Index()
 {
  var model = new CustomersViewModel()
  {
  Customers = null,
  PagingInfo = new PagingInfo()
  {
   CurrentPage=1,
   ItemsPerPage= 10,
   PageOptions = new List() { 10,25, 50, 100},
   ShowPageOptions= true,
   TotalItems=1
  }
  };
  return View(model);
 }

 public ActionResult GetCustomers(PagingInfo PagingData)
 {
  var db = new MyDbContext();
  var model = GridViewModelProvider.GetCustomersViewModel(db, PagingData);  
  return PartialView("_CustomersPartial", model);
 }

 public ActionResult About()
 {
  ViewBag.Message = "您的应用程序描述页面。";

  return View();
 }

 public ActionResult Contact()
 {
  ViewBag.Message = "您的联系页面。";

  return View();
 }
 }

Home视图文件夹下:

_CustomersPartial.cshtml

@model mesoft.gridview.Models.CustomersViewModel

@*在这里写下返回的数据的详细信息*@



 @if (Model.Customers.Any())
 {
  foreach (var c in Model.Customers)
  {
  
  }
 }
 else
 {
  
 }

 @Html.Raw(ViewBag.Script)
 
@(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().Id)) @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().CompanyName)) @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().ContactTitle)) @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().Country)) @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().City)) @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().Address)) @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().Phone)) @Html.DisplayNameFor(x=> x.Customers.FirstOrDefault().Founded)
@c.Id @c.CompanyName @c.ContactTitle @c.Country @c.City @c.Address @c.Phone @c.Founded
警告! 没有客户找到!

_GridViewPartial.cshtml

@model mesoft.gridview.Models.CustomersViewModel


@{ string[] cityFilters = {"Istanbul", "Trabzon", "Ankara", "Izmir", "Samsun", "Erzurum"}; } 根据城市筛选:
@*Data Will Load Here*@

About.cshtml

@{
 ViewBag.Title = "About";
}

@ViewBag.Title.

@ViewBag.Message

#

Contact.cshtml

@{
 ViewBag.Title = "Contact";
}

@ViewBag.Title.

@ViewBag.Message

Support: [email protected]

Index.cshtml

@model mesoft.gridview.Models.CustomersViewModel

@{
 ViewBag.Title = "Home Page";
}

Gridview

简单易用,开发简单

Learn more »

@Html.Partial("_GridViewPartial")
@section Scripts { }

Shared文件夹下:

_Layout.cshtml




 
 
 @ViewBag.Title -GridView的用法示例应用程序
 @Styles.Render("~/Content/css")
 @Scripts.Render("~/bundles/modernizr")



 
 
@RenderBody()

© @DateTime.Now.Year - WuLex

@Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false)

运行结果如图:

灵活掌握Asp.net MVC中GridView的使用方法_第1张图片

为大家附3个精彩的专题:

ASP.NET控件使用手册

ASP.NET数据绑定控件使用汇总

ASP.NET控件使用汇总

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(灵活掌握Asp.net MVC中GridView的使用方法)