一、新建Common文件夹,将公共类放入到此文件夹中
1、新建GridPager类
public class GridPager { public int rows { get; set; }//每页行数 public int page { get; set; }//当前页是第几页 public string order { get; set; }//排序方式 public string sort { get; set; }//排序列 public int totalRows { get; set; }//总行数 public int totalPages //总页数 { get { return (int)Math.Ceiling((float)totalRows / (float)rows); } } }
2、新建SortingAndPaging类
添加引入:using System.Linq.Expressions;
using System.Reflection;
public class SortingAndPaging { /// <summary> /// 排序 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="sortExpression"></param> /// <param name="sortDirection"></param> /// <returns></returns> public static IQueryable<T> DataSorting<T>(IQueryable<T> source, string sortExpression, string sortDirection) { string sortingDir = string.Empty; if (sortDirection.ToUpper().Trim() == "ASC") sortingDir = "OrderBy"; else if (sortDirection.ToUpper().Trim() == "DESC") sortingDir = "OrderByDescending"; ParameterExpression param = Expression.Parameter(typeof(T), sortExpression); PropertyInfo pi = typeof(T).GetProperty(sortExpression); Type[] types = new Type[2]; types[0] = typeof(T); types[1] = pi.PropertyType; Expression expr = Expression.Call(typeof(Queryable), sortingDir, types, source.Expression, Expression.Lambda(Expression.Property(param, sortExpression), param)); IQueryable<T> query = source.AsQueryable().Provider.CreateQuery<T>(expr); return query; } /// <summary> /// 分页 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="pageNumber"></param> /// <param name="pageSize"></param> /// <returns></returns> public static IQueryable<T> DataPaging<T>(IQueryable<T> source, int pageNumber, int pageSize) { if (pageNumber <= 1) { return source.Take(pageSize); } else { return source.Skip((pageNumber - 1) * pageSize).Take(pageSize); } } /// <summary> /// 排序并分页 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="sortExpression"></param> /// <param name="sortDirection"></param> /// <param name="pageNumber"></param> /// <param name="pageSize"></param> /// <returns></returns> public static IQueryable<T> SortingPaging<T>(IQueryable<T> source, string sortExpression, string sortDirection, int pageNumber, int pageSize) { IQueryable<T> query = DataSorting<T>(source, sortExpression, sortDirection); return DataPaging(query, pageNumber, pageSize); } }
3、新建Suggestion类(静态类)
public static class Suggestion { public static string PlaseChooseToOperatingRecords { get { return "请选择要操作的记录"; } } public static string AreYouLogOff { get { return "您确定要注销系统吗?"; } } public static string Cancel { get { return "取消"; } } public static string CanNotOperationHasTheAudit { get { return "不能操作已经审核的记录"; } } public static string Check { get { return "审核"; } } public static string CheckFail { get { return "审核失败"; } } public static string CheckSucceed { get { return "审核成功"; } } public static string ClearLossJobs { get { return "清理离线任务"; } } public static string Close { get { return "关闭"; } } public static string CloseAll { get { return "关闭全部"; } } public static string CloseLeft { get { return "关闭左侧标签"; } } public static string CloseOther { get { return "除此之外全部关闭"; } } public static string CloseRight { get { return "关闭右侧标签"; } } public static string Create { get { return "创建"; } } public static string Delete { get { return "删除"; } } public static string DeleteFail { get { return "删除失败"; } } public static string DeleteSucceed { get { return "删除成功"; } } public static string Details { get { return "详细"; } } public static string Disable { get { return "不可用"; } } public static string Edit { get { return "编辑"; } } public static string EditFail { get { return "修改失败"; } } public static string EditSucceed { get { return "修改成功"; } } public static string Export { get { return "导出"; } } public static string InsertFail { get { return "创建失败"; } } public static string InsertSucceed { get { return "创建成功"; } } public static string Loading { get { return "加载中"; } } public static string LoginSucceed { get { return "登录成功,您可以继续操作!"; } } public static string LogOff { get { return "安全退出"; } } public static string NoAnyChanges { get { return "没有作任何修改"; } } public static string Operate { get { return "操作"; } } public static string PrimaryRepeat { get { return "主键重复"; } } public static string Query { get { return "查询"; } } public static string Reload { get { return "刷新"; } } public static string Return { get { return "返回"; } } public static string Save { get { return "保存"; } } public static string Select { get { return "选择"; } } public static string SetFail { get { return "设置失败"; } } public static string SetSucceed { get { return "设置成功"; } } public static string SwitchingSkin { get { return "切换主题,系统将重新加载?"; } } public static string Tip { get { return "提示"; } } public static string UnCheck { get { return "反审核"; } } public static string UnCheckFail { get { return "反审核失败"; } } public static string UnCheckSucceed { get { return "反审核成功"; } } public static string UnSelect { get { return "反选"; } } public static string Update { get { return "更新"; } } public static string UpdateFail { get { return "更新失败"; } } public static string UpdateSucceed { get { return "更新成功"; } } public static string UpLoad { get { return "上传"; } } public static string UserTimeOver { get { return "用户登录超时,请重新登录"; } } public static string Welcome { get { return "您好,欢迎您"; } } public static string YouCanOnlyOperateARecord { get { return "一次只能操作一条记录"; } } public static string YouWantToDeleteTheSelectedRecords { get { return "您确定要删除所选记录吗?"; } } }
4、新建ValidationError类,(包含两个类)
public class ValidationError { public ValidationError() { } public string ErrorMessage { get; set; } } public class ValidationErrors : List<ValidationError> { /// <summary> /// 添加错误 /// </summary> /// <param name="errorMessage">信息描述</param> public void Add(string errorMessage) { base.Add(new ValidationError { ErrorMessage = errorMessage }); } /// <summary> /// 获取错误集合 /// </summary> public string Error { get { string error = ""; this.All(a => { error += a.ErrorMessage; return true; }); return error; } } }
5、新建JsonHandler类,(包含两个类)
public class JsonHandler { public static JsonMessage CreateMessage(int ptype, string pmessage, string pvalue) { JsonMessage json = new JsonMessage() { type = ptype, message = pmessage, value = pvalue }; return json; } public static JsonMessage CreateMessage(int ptype, string pmessage) { JsonMessage json = new JsonMessage() { type = ptype, message = pmessage, }; return json; } } public class JsonMessage { public int type { get; set; } public string message { get; set; } public string value { get; set; } }
6、新建ToJsonResult类,继承JsonResult,添加引用
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
public class ToJsonResult : JsonResult { const string error = "该请求已被封锁,因为敏感信息透露给第三方网站,这是一个GET请求时使用的。为了可以GET请求,请设置JsonRequestBehavior AllowGet。"; /// <summary> /// 格式化字符串 /// </summary> public string FormateStr { get; set; } public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(error); } HttpResponseBase response = context.HttpContext.Response; if (!String.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonstring = serializer.Serialize(Data); //string p = @"\/Date((d+)+d+)\/"; string p = @"\/Date(d+)\/"; MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); Regex reg = new Regex(p); jsonstring = reg.Replace(jsonstring, matchEvaluator); response.Write(jsonstring); } } /// <summary> /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串 /// </summary> private string ConvertJsonDateToDateString(Match m) { string result = string.Empty; string p = @"d"; var cArray = m.Value.ToCharArray(); StringBuilder sb = new StringBuilder(); Regex reg = new Regex(p); for (int i = 0; i < cArray.Length; i++) { if (reg.IsMatch(cArray[i].ToString())) { sb.Append(cArray[i]); } } // reg.Replace(m.Value; DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(sb.ToString())); dt = dt.ToLocalTime(); result = dt.ToString("yyyy-MM-dd"); return result; } }
7、新建ExportExcelResult类,继承ActionResult,添加引用
using System.Text;
using System.Web.Mvc;
using System.IO;
using ClosedXML.Excel;
public class ExportExcelResult : ActionResult { public string SheetName { get; set; } public string FileName { get; set; } public DataTable ExportData { get; set; } public ExportExcelResult() { } public override void ExecuteResult(ControllerContext context) { if (ExportData == null) { throw new InvalidDataException("ExportData"); } if (string.IsNullOrWhiteSpace(this.SheetName)) { this.SheetName = "Sheet1"; } if (string.IsNullOrWhiteSpace(this.FileName)) { this.FileName = string.Concat( "ExportData_", DateTime.Now.ToString("yyyyMMddHHmmss"), ".xlsx"); } this.ExportExcelEventHandler(context); } /// <summary> /// Exports the excel event handler. /// </summary> /// <param name="context">The context</param> private void ExportExcelEventHandler(ControllerContext context) { try { var workbook = new XLWorkbook(); if (this.ExportData != null) { context.HttpContext.Response.Clear(); // 编码 context.HttpContext.Response.ContentEncoding = Encoding.UTF8; // 设置网页ContentType context.HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // 导出名字 var browser = context.HttpContext.Request.Browser.Browser; var exportFileName = browser.Equals("Firefox", StringComparison.OrdinalIgnoreCase) ? this.FileName : HttpUtility.UrlEncode(this.FileName, Encoding.UTF8); context.HttpContext.Response.AddHeader( "Content-Disposition", string.Format("attachment;filename={0}", exportFileName)); // Add all DataTables in the DataSet as a worksheets workbook.Worksheets.Add(this.ExportData, this.SheetName); using (var memoryStream = new MemoryStream()) { workbook.SaveAs(memoryStream); memoryStream.WriteTo(context.HttpContext.Response.OutputStream); memoryStream.Close(); } } workbook.Dispose(); } catch (Exception ex) { throw; } } }
二、controllers下新建BaseController.cs,继承Controller
public class BaseController : Controller { // // GET: /Base/ protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) { return new ToJsonResult { Data = data, ContentEncoding = contentEncoding, ContentType = contentType, JsonRequestBehavior = behavior, FormateStr = "yyyy-MM-dd HH:mm:ss" }; } /// <summary> /// 返回JsonResult.24 /// </summary> /// <param name="data">数据</param> /// <param name="behavior">行为</param> /// <param name="format">json中dateTime类型的格式</param> /// <returns>Json</returns> protected JsonResult MyJson(object data, JsonRequestBehavior behavior, string format) { return new ToJsonResult { Data = data, JsonRequestBehavior = behavior, FormateStr = format }; } /// <summary> /// 返回JsonResult42 /// </summary> /// <param name="data">数据</param> /// <param name="format">数据格式</param> /// <returns>Json</returns> protected JsonResult MyJson(object data, string format) { return new ToJsonResult { Data = data, FormateStr = format }; } }