灵活掌握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);
 }
 }
 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;
 }
 }
 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;
 }
 }
 /// <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);
  }
 }
 }

MyDbContext.CS代码:

 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);
 }
 }

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<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();
 }
 }

Home视图文件夹下:

_CustomersPartial.cshtml

@model mesoft.gridview.Models.CustomersViewModel

@*在这里写下返回的数据的详细信息*@
<span class="gridview-data-details" style="display:none;">@Html.Raw(Model.JsonPagingInfo)</span>

<table class="table table-bordered table-striped">
 <thead>
 <tr class="gridview-list-header">
  <th>
  @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().Id))
  </th>
  <th class="sortable" data-sort="CompanyName">
  @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().CompanyName))
  </th>
  <th class="sortable" data-sort="ContactTitle">
  @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().ContactTitle))
  </th>
  <th>
  @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().Country))
  </th>
  <th>
  @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().City))
  </th>
  <th>
  @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().Address))
  </th>
  <th>
  @(Html.DisplayNameFor(x => x.Customers.FirstOrDefault().Phone))
  </th>
  <th>
  @Html.DisplayNameFor(x=> x.Customers.FirstOrDefault().Founded)
  </th>
 </tr>
 </thead>

 <tbody id="CustomersTable" class="gridview-list-items">
 @if (Model.Customers.Any())
 {
  foreach (var c in Model.Customers)
  {
  <tr>
   <td class="value">@c.Id</td>
   <td class="value">@c.CompanyName</td>
   <td class="value">@c.ContactTitle</td>
   <td class="value">@c.Country</td>
   <td class="value">@c.City</td>
   <td class="Description">@c.Address</td>
   <td class="value">@c.Phone</td>
   <td>@c.Founded</td>
  </tr>
  }
 }
 else
 {
  <tr>
  <td colspan="8">
   <div class="alert alert-warning alert-dismissable">
   <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
   <strong>警告!</strong> 没有客户找到!
   </div>
  </td>
  </tr>
 }

 @Html.Raw(ViewBag.Script)
 </tbody>

</table>

_GridViewPartial.cshtml

@model mesoft.gridview.Models.CustomersViewModel

<!-- GRIDVIEW-->
<div class="gridview gridview1">
 <!-- GridView Header-->
 <div class="gridview-header">
 <!--GridView的头的左边部分-->
 <div class="col-sm-6">
  <div class="gridview-search">
  <div class="search input-group">
   <input class="form-control" placeholder="Search" type="search">
   <span class="input-group-btn">
   <button class="btn btn-default" type="button">
    <span class="fa fa-search"></span>
    <span class="sr-only">Search</span>
   </button>
   </span>
  </div>
  </div>
 </div>

 <!-- GridView的头右边部分-->
 <div class="col-sm-6 text-right">
  <!-- 这里添加任何筛选操作-->
  @{
  string[] cityFilters = {"Istanbul", "Trabzon", "Ankara", "Izmir", "Samsun", "Erzurum"};
  }

  根据城市筛选:
  <div class="btn-group">
  <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
   Select City <span class="caret"></span>
  </button>
  <ul class="dropdown-menu filter-parent" role="menu">
   @foreach (var city in cityFilters)
   {
   <li><a href="#" class="filter"
    data-filter-column="City"
    data-filter-value="@city"
    data-filter-operator="@mesoft.gridview.Models.FilterOperator.Equals"
    data-filter-conjunction="@mesoft.gridview.Models.FilterConjunction.And">@city</a></li>
   }
   <li class="divider"></li>
   <li class="active"><a href="#" class="filter"
     data-filter-column="City"
     data-filter-value="All">All</a></li>
  </ul>
  </div>
 </div>
 </div>

 <!-- GridView ViewPort-->
 <div class="gridview-viewport" id="viewport"
  data-getdata-function="@Url.Action("GetCustomers", "Home")"
  data-default-pagesize="10">
 <div class="gridview-canvas" style="min-height:400px;">
  @*Data Will Load Here*@
 </div>
 <div class="loading gridview gridview-loader">
  <img src="~/content/images/loading.gif" />
 </div>
 </div>
 <!-- GridView的分页区域-->
 <div class="gridview-footer">
 @Html.DisplayFor(x => x.PagingInfo, "Pager")
 </div>
</div>

About.cshtml

@{
 ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<p>#</p>

Contact.cshtml

@{
 ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<address>
 <strong>Support:</strong> <a href="827937686@qq.com">827937686@qq.com</a><br />
</address>

Index.cshtml

@model mesoft.gridview.Models.CustomersViewModel

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

<div class="jumbotron">
 <h1>Gridview</h1>
 <p class="lead">简单易用,开发简单</p>
 <p><a href="#" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<!-- GRIDVIEW Area-->
<div class="row">
 @Html.Partial("_GridViewPartial")
</div>

@section Scripts {
 <script>
 $('.gridview1').meGridView();
 //$('.gridview2').meGridView();
 </script>

}

Shared文件夹下:

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>@ViewBag.Title -GridView的用法示例应用程序</title>
 @Styles.Render("~/Content/css")
 @Scripts.Render("~/bundles/modernizr")

</head>
<body>
 <div class="navbar navbar-inverse navbar-fixed-top">
 <div class="container">
  <div class="navbar-header">
  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
  </button>
  @Html.ActionLink("GridView", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
  </div>
  <div class="navbar-collapse collapse">
  <ul class="nav navbar-nav">
   <li>@Html.ActionLink("Home", "Index", "Home")</li>
   <li>@Html.ActionLink("About", "About", "Home")</li>
   <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
  </ul>
  @*@Html.Partial("_LoginPartial")*@
  </div>
 </div>
 </div>
 <div class="container body-content">
 @RenderBody()
 <hr />
 <footer>
  <p>© @DateTime.Now.Year - WuLex</p>
 </footer>
 </div>

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

运行结果如图:

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

ASP.NET控件使用手册

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

ASP.NET控件使用汇总

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

(0)

相关推荐

  • Asp.NET MVC中使用SignalR实现推送功能

    一.简介 Signal 是微软支持的一个运行在 Dot NET 平台上的 html websocket 框架.它出现的主要目的是实现服务器主动推送(Push)消息到客户端页面,这样客户端就不必重新发送请求或使用轮询技术来获取消息. 可访问其官方网站:https://github.com/SignalR/ 获取更多资讯. 二.Asp.net SignalR 是个什么东东 Asp.net SignalR是微软为实现实时通信的一个类库.一般情况下,SignalR会使用JavaScript的长轮询(lo

  • ASP.NET MVC 微信JS-SDK认证

    ASP.NET MVC微信JS-SDK认证,具体内容: 写在前面 前阵子因为有个项目需要做微信自定义分享功能,因而去研究了下微信JS-SDK相关知识. 此文做个简单的记(tu)录(cao)... 开始 所有的东西都从文档开始:微信JSSDK说明文档 项目需要用到的是分享接口不过使用微信JS-SDK之前,需要做JS接口认证. 认证如下: 步骤一:绑定域名 步骤二:引入JS文件 步骤三:通过config接口注入权限验证配置 步骤四:通过ready接口处理成功验证 步骤五:通过error接口处理失败验

  • ASP.NET MVC下的四种验证编程方式[续篇]

    在<ASP.NET MVC的四种验证编程方式>一文中我们介绍了ASP.NET MVC支持的四种服务端验证的编程方式("手工验证"."标注ValidationAttribute特性"."让数据类型实现IValidatableObject或者IDataErrorInfo"),那么在ASP.NET MVC框架内部是如何提供针对这四种不同编程方式的支持的呢?接下来我们就来聊聊这背后的故事. 一.ModelValidator与ModelVali

  • ASP.NET MVC使用EPPlus,导出数据到Excel中

    好久没写博客了,今天特地来更新一下,今天我们要学习的是如何导出数据到Excel文件中,这里我使用的是免费开源的Epplus组件. 源代码下载:https://github.com/caofangsheng93/ExcelExportInMvc 介绍 这篇文章,介绍的是怎样导出数据到Excel文件中,大多数的后端程序都有报表功能:把显示在Grid中的数据导出到Excel文件中,这篇文章中使用的是EPPlus组件. EPPlus是一个基于OOXML[Open Extended Markup Lang

  • 详解ASP.NET MVC的筛选器

    在ActionInvoker对Action的执行过程中,除了通过利用ActionDescriptor对Action方法的执行,以及之前进行的Model绑定与验证之外,还具有一个重要的工作,那就是对相关筛选器(Filter)的执行.ASP.NET MVC的筛选器是一种基于AOP(面向方面编程)的设计,我们将一些非业务的逻辑实现在相应的筛选器中,然后以一种横切(Crosscutting)的方式应用到对应的Action方法.当Action方法执行前后,这些筛选器会自动执行.ASP.NET MVC提供了

  • ASP.NET Core MVC 配置全局路由前缀

    ASP.NET Core MVC 配置全局路由前缀 前言 大家好,今天给大家介绍一个 ASP.NET Core MVC 的一个新特性,给全局路由添加统一前缀.严格说其实不算是新特性,不过是Core MVC特有的. 应用背景 不知道大家在做 Web Api 应用程序的时候,有没有遇到过这种场景,就是所有的接口都是以 /api 开头的,也就是我们的api 接口请求地址是像这样的: http://www.example.com/api/order/333 或者是这样的需求 http://www.exa

  • ASP.NET MVC后台参数验证的几种方式

    前言 参数验证是一个常见的问题,无论是前端还是后台,都需对用户输入进行验证,以此来保证系统数据的正确性.对于web来说,有些人可能理所当然的想在前端验证就行了,但这样是非常错误的做法,前端代码对于用户来说是透明的,稍微有点技术的人就可以绕过这个验证,直接提交数据到后台.无论是前端网页提交的接口,还是提供给外部的接口,参数验证随处可见,也是必不可少的.总之,一切用户的输入都是不可信的. 参数验证有许多种方式进行,下面以mvc为例,列举几种常见的验证方式,假设有一个用户注册方法 [HttpPost]

  • ASP.NET MVC阿里大于短信接口开发短信群发能

    互联网上有许多公司提供短信接口服务,诸如网易云信.阿里大于等等.我在自己项目里需要使用到短信服务起到通知作用,实际开发周期三天,完成配置.开发和使用,总的说,阿里大于提供的接口易于开发,非常的方便,短信费用是计数缴纳的,作为个人开发者,我使用的服务业务产生的费用为0.045¥/条(10万条以下). 现在要实现一个例会短信群发通知的功能,所有被通知对象信息均存于Mysql中,应用架构采用asp.net MVC .首先准备好获取的API各项(以下各项服务参数都需要在大于官网上申请), 申请好自己的短

  • ASP.NET MVC自定义错误页面真的简单吗?

    如果你在设置asp.net mvc自定义错误页面时遇到问题,这并不止你一个人.惊讶之余你的做法是正确的,没有起到作用的原因是其一部分错误是由asp.net管道处理的,另一部分是由iis直接处理. 通常情况 (我期望是这种情况,在一些其他框架/服务器上) 我们只需要在一个地方配置自定义错误页就可以了,无论怎么哪儿引发的错误.就像这样︰ <customErrors mode="On"> <error code="404" path="404.

  • [Asp.Net MVC4]验证用户登录实现实例

    最近我们要做一个仿sina的微博,碰巧的是我最近在学习mvc,就想用mvc技术实现这个项目. 既然是微博,那不用想也应该知道肯定要有用户登陆,但是和常规的asp.NET登陆又不一样,以下是我一下午+一晚上的研究成果~~~ 首先,建好数据库以及表,这就不用说了吧. 下面说一下主要的结构 控制器: HomeController 这是主页的控制器 LoginController 这是登陆的控制器 类: CDBTemplate.cs 这是数据库数据对应的类,里边描述的是数据库的结构 //////////

  • Asp.net MVC中获取控制器的名称的方法

    1.视图中 string controller = ViewContext.RouteData.Route.GetRouteData(this.Context).Values["controller"].ToString(); string controller = ViewContext.RouteData.Values["controller"].ToString(); 2.控制器的action中 string controller = RouteData.Ro

随机推荐