搜尋
首頁後端開發C#.Net教程靈活掌握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<Customer> 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<Func<T,bool>> GetExpression<T>(IList<FilterObject> filters)
{
 if (filters.Count == 0)
 return null;
 
 ParameterExpression param = Expression.Parameter(typeof(T), "t");
 Expression exp = null;
 
 if (filters.Count == 1)
 exp = GetExpression<T>(param, filters[0]);
 else if (filters.Count == 2)
 exp = GetExpression<T>(param, filters[0], filters[1]);
 else
 {
 while (filters.Count > 0)
 {
  var f1 = filters[0];
  var f2 = filters[1];
 
  if (exp == null)
  exp = GetExpression<T>(param, filters[0], filters[1]);
  else
  exp = Expression.AndAlso(exp, GetExpression<T>(param, filters[0], filters[1]));
 
  filters.Remove(f1);
  filters.Remove(f2);
 
  if (filters.Count == 1)
  {
  exp = Expression.AndAlso(exp, GetExpression<T>(param, filters[0]));
  filters.RemoveAt(0);
  }
 }
 }
 
 return Expression.Lambda<Func<T, bool>>(exp, param);
}
 
private static Expression GetExpression<T>(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<T> (ParameterExpression param, FilterObject filter1, FilterObject filter2)
{
 Expression bin1 = GetExpression<T>(param, filter1);
 Expression bin2 = GetExpression<T>(param, filter2);
 
 return Expression.AndAlso(bin1, bin2);
}
}

   

MyDbContext.CS程式碼:

public class PagingInfo
{
public List<int> 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<FilterObject> 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;
}
}

   

HomeController.cscom omersPartial.cshtml

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<int>() { 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<Customer> GetResources(IQueryable<Customer> 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;
}
}

   

_GridViewPartial. cshtml

/// <summary>
/// 启用查询谓词的高效,动态组合。
/// </summary>
public static class PredicateBuilder
{
/// <summary>
/// 创建一个计算结果为true的谓词。
/// </summary>
public static Expression<Func<T, bool>> True<T>() { return param => true; }
 
/// <summary>
/// 创建一个计算结果为false的谓词
/// </summary>
public static Expression<Func<T, bool>> False<T>() { return param => false; }
 
/// <summary>
/// 创建一个从指定的lambda表达式的谓词表达式。
/// </summary>
public static Expression<Func<T, bool>> Create<T>(Expression<Func<T, bool>> predicate) { return predicate; }
 
/// <summary>
/// 结合了第二第一谓词使用逻辑“and”。
/// </summary>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
 return first.Compose(second, Expression.AndAlso);
}
 
/// <summary>
/// 结合了第二第一谓词使用逻辑“or”。
/// </summary>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
 return first.Compose(second, Expression.OrElse);
}
 
/// <summary>
///否定谓词
/// </summary>
public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expression)
{
 var negated = Expression.Not(expression.Body);
 return Expression.Lambda<Func<T, bool>>(negated, expression.Parameters);
}
 
/// <summary>
/// 使用指定的合并函数,合并第二和第一表达式
/// </summary>
static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> 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<T>(merge(first.Body, secondBody), first.Parameters);
}
 
class ParameterRebinder : ExpressionVisitor
{
 readonly Dictionary<ParameterExpression, ParameterExpression> map;
 
 ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
 {
 this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
 }
 
 public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> 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);
 }
}
}

   

About.cshtml

public class MyDbContext : DbContext
{
public MyDbContext()
 : base("DefaultConnection")
{
 
}
 
public DbSet<Customer> Customers { get; set; }
 
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ 
 modelBuilder.Entity<Customer>().Property(c => c.CompanyName).HasMaxLength(40);
 modelBuilder.Entity<Customer>().Property(c => c.ContactTitle).HasMaxLength(40);
}
}

   

   

Shared資料夾下:

_Layout.cshtml

public class HomeController : Controller
{
public ActionResult Index()
{
 var model = new CustomersViewModel()
 {
 Customers = null,
 PagingInfo = new PagingInfo()
 {
  CurrentPage=1,
  ItemsPerPage= 10,
  PageOptions = new List<int>() { 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();
}
}

   

運作結果如圖:

更多靈活掌握Asp.net MVCGridView的使用方法相關文章請注意PHPP網!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
C#.NET用於網絡,桌面和移動開發C#.NET用於網絡,桌面和移動開發Apr 25, 2025 am 12:01 AM

C#和.NET適用於Web、桌面和移動開發。 1)在Web開發中,ASP.NETCore支持跨平台開發。 2)桌面開發使用WPF和WinForms,適用於不同需求。 3)移動開發通過Xamarin實現跨平台應用。

C#.NET生態系統:框架,庫和工具C#.NET生態系統:框架,庫和工具Apr 24, 2025 am 12:02 AM

C#.NET生態系統提供了豐富的框架和庫,幫助開發者高效構建應用。 1.ASP.NETCore用於構建高性能Web應用,2.EntityFrameworkCore用於數據庫操作。通過理解這些工具的使用和最佳實踐,開發者可以提高應用的質量和性能。

將C#.NET應用程序部署到Azure/AWS:逐步指南將C#.NET應用程序部署到Azure/AWS:逐步指南Apr 23, 2025 am 12:06 AM

如何將C#.NET應用部署到Azure或AWS?答案是使用AzureAppService和AWSElasticBeanstalk。 1.在Azure上,使用AzureAppService和AzurePipelines自動化部署。 2.在AWS上,使用AmazonElasticBeanstalk和AWSLambda實現部署和無服務器計算。

C#.NET:強大的編程語言簡介C#.NET:強大的編程語言簡介Apr 22, 2025 am 12:04 AM

C#和.NET的結合為開發者提供了強大的編程環境。 1)C#支持多態性和異步編程,2).NET提供跨平台能力和並發處理機制,這使得它們在桌面、Web和移動應用開發中廣泛應用。

.NET框架與C#:解碼術語.NET框架與C#:解碼術語Apr 21, 2025 am 12:05 AM

.NETFramework是一個軟件框架,C#是一種編程語言。 1..NETFramework提供庫和服務,支持桌面、Web和移動應用開發。 2.C#設計用於.NETFramework,支持現代編程功能。 3..NETFramework通過CLR管理代碼執行,C#代碼編譯成IL後由CLR運行。 4.使用.NETFramework可快速開發應用,C#提供如LINQ的高級功能。 5.常見錯誤包括類型轉換和異步編程死鎖,調試需用VisualStudio工具。

揭開c#.net的神秘面紗:初學者的概述揭開c#.net的神秘面紗:初學者的概述Apr 20, 2025 am 12:11 AM

C#是一種由微軟開發的現代、面向對象的編程語言,.NET是微軟提供的開發框架。 C#結合了C 的性能和Java的簡潔性,適用於構建各種應用程序。 .NET框架支持多種語言,提供垃圾回收機制,簡化內存管理。

C#和.NET運行時:它們如何一起工作C#和.NET運行時:它們如何一起工作Apr 19, 2025 am 12:04 AM

C#和.NET運行時緊密合作,賦予開發者高效、強大且跨平台的開發能力。 1)C#是一種類型安全且面向對象的編程語言,旨在與.NET框架無縫集成。 2).NET運行時管理C#代碼的執行,提供垃圾回收、類型安全等服務,確保高效和跨平台運行。

C#.NET開發:入門的初學者指南C#.NET開發:入門的初學者指南Apr 18, 2025 am 12:17 AM

要開始C#.NET開發,你需要:1.了解C#的基礎知識和.NET框架的核心概念;2.掌握變量、數據類型、控制結構、函數和類的基本概念;3.學習C#的高級特性,如LINQ和異步編程;4.熟悉常見錯誤的調試技巧和性能優化方法。通過這些步驟,你可以逐步深入C#.NET的世界,並編寫高效的應用程序。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境