using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using System.Data.Entity; using System.Data.SqlClient; using System.Data.Entity.Validation; using System.ComponentModel; using System.Reflection; using System.Web.Security; using formula; namespace formula { public abstract class BaseController : Controller { #region 处理不存在的Action protected override void HandleUnknownAction(string actionName) { if (Request.HttpMethod == "POST") { HttpContext.ClearError(); HttpContext.Response.Clear(); HttpContext.Response.StatusCode = 500; HttpContext.Response.Write("没有Action:" + actionName); HttpContext.Response.End(); } // 搜索文件是否存在 var filePath = ""; if (RouteData.DataTokens["area"] != null) filePath = string.Format("~/Areas/{2}/Views/{1}/{0}.cshtml", actionName, RouteData.Values["controller"], RouteData.DataTokens["area"]); else filePath = string.Format("~/Views/{1}/{0}.cshtml", actionName, RouteData.Values["controller"]); if (System.IO.File.Exists(Server.MapPath(filePath))) { View(filePath).ExecuteResult(ControllerContext); } else { HttpContext.ClearError(); HttpContext.Response.Clear(); HttpContext.Response.StatusCode = 500; HttpContext.Response.Write("没有Action:" + actionName); HttpContext.Response.End(); } } #endregion #region 基类Json方法重载 protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) { NewtonJsonResult result = new NewtonJsonResult() { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior }; return result; } protected override JsonResult Json(object data, string contentType, Encoding contentEncoding) { NewtonJsonResult result = new NewtonJsonResult() { Data = data, ContentType = contentType, ContentEncoding = contentEncoding }; return result; } #endregion #region 异常处理 protected override void OnException(ExceptionContext filterContext) { Exception exp = filterContext.Exception; if (string.IsNullOrEmpty(exp.Message)) exp = exp.GetBaseException(); if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) { var response = filterContext.RequestContext.HttpContext.Response; response.Clear(); response.Write(exp.Message); response.StatusCode = 500; response.End(); } } #endregion } }
2、查询构造器QueryBuilder:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Web.Mvc; namespace formula { [ModelBinder(typeof(QueryBuilderBinder))] public class QueryBuilder : SearchCondition { public int page { get; set; } public int rows { get; set; } public string sort { get; set; } public string order { get; set; } public int total { get; set; } public string getOrderByString(bool hasOrderBy = true) { var sortFields = this.sort.Split(','); var sortOrders = this.order.Split(','); string str = ""; for (int i = 0; i < sortFields.Length; i++) { str += sortFields[i] + " " + sortOrders[i] + ","; } if (hasOrderBy && str != "") str = "order by " + str; return str.Trim(','); } } public class SearchCondition { public string fields = "*"; private List<ConditionItem> quickItems = new List<ConditionItem>(); private List<ConditionItem> complexItems = new List<ConditionItem>(); public SearchCondition add(string field, string method, object val, bool isQuickSearch = false) { //处理日期型数据 if (method == "<" || method == "<=") { if (val.GetType() == typeof(DateTime)) { DateTime t = (DateTime)val; val = t.Date.AddHours(23).AddMinutes(59).AddSeconds(59); } } ConditionItem item = new ConditionItem(field, method, val); if (isQuickSearch) quickItems.Add(item); else complexItems.Add(item); return this; } public string getWhereString(bool hasWhere = true) { if (quickItems.Count == 0 && complexItems.Count == 0) return ""; string strWhere = ""; if (quickItems.Count > 0) strWhere += " and (" + getGourpWhereString(quickItems, true) + ")"; if (complexItems.Count > 0) strWhere += " and (" + getGourpWhereString(complexItems, false) + ")"; if (hasWhere) strWhere = " where " + strWhere.Substring(4); else strWhere = " and " + strWhere.Substring(4); return strWhere; } #region 私有方法 private string getGourpWhereString(List<ConditionItem> list, bool isOrRelation = false) { if (list.Count == 0) return ""; string strWhere = ""; for (int i = 0; i < list.Count(); i++) { var item = list[i]; string str = item.getWhereString(); if (isOrRelation) { strWhere += " or " + str; } else { strWhere += " and " + str; } } strWhere = strWhere.Substring(4); return strWhere; } #endregion } public class ConditionItem { public ConditionItem(string field, string method, object val) { this.field = field; this.method = method; this.value = val; } public string field { get; set; } public string method { get; set; } public object value { get; set; } public string getWhereString() { var item = this; switch (item.method) { case "=": case "<": case ">": case "<=": case ">=": case "<>": return string.Format("{0} {1} '{2}'", item.field, item.method, item.value); case "in": string v = ""; if (item.value is ICollection) { ICollection<string> collection = item.value as ICollection<string>; v = string.Join("','", collection.ToArray<string>()); return string.Format("{0} in('{1}')", item.field, v); } else { v = item.value.ToString().Replace(",", "','"); } return string.Format("{0} in ('{1}')", item.field, v); case "between": object[] objs = item.value as object[]; return string.Format("{0} between '{1}' and '{2}'", item.field, objs[0], objs[1]); case "inLike": string[] arr = null; if (item.value is ICollection) { ICollection<string> collection = item.value as ICollection<string>; arr = collection.ToArray<string>(); } else { arr = item.value.ToString().Split(',', ','); } string str = ""; foreach (string s in arr) { str += string.Format("or {0} like '%{1}%'", item.field, s); } return "(" + str.Substring(3) + ")"; case "day": DateTime dt = DateTime.Now; if (!DateTime.TryParse(item.value.ToString(), out dt)) { throw new BuessinessException("查询条件不能转化为日期时间"); } string start = dt.Date.ToString("yyyy-MM-dd"); string end = dt.Date.AddDays(1).ToString("yyyy-MM-dd"); return string.Format("{0} between '{1}' and '{2}'", item.field, start, end); case "startWith": return string.Format("{0} like '{1}%'", item.field, item.value); case "endWith": return string.Format("{0} like '%{1}'", item.field, item.value); default: return ""; } } } }
3、查询构造器QueryBuilder的创建方法QueryBuilderBinder: