利用ASP.NET MVC+EasyUI+SqlServer搭建企业开发框架

我们要搭建的框架是企业级开发框架,适用用企业管理信息系统的开发,如:OA、HR等

1、框架名称:sampleFrame。

2、搭建原则:最少知识原则。

3、先定义一个简单的编码规范:除类名和接口名外,其余首字母小写。

4、准备开发环境:vs2010及以上(mvc4)、sqlserver、jquery2.0和easyui1.4.5

首先来看一下列表页面的效果图:

我们期望简洁带前台代码,如下:

<table id="dataGrid" class="easyui-datagrid" url="getList" toolbar="#toolbar">
 <thead>
 <tr>
  <th field="customerId" sortable="true" data-options="sortable:true" width="50">
  customerId
  </th>
  <th field="companyName" data-options="sortable:true" width="50">
  companyName
  </th>
  <th field="phone" width="50">
  phone
  </th>
  <th field="address" width="50">
  address
  </th>
 </tr>
 </thead>
</table>
<div id="toolbar">
 <div>
 <a class="easyui-linkbutton" iconcls="icon-add" onclick="add();">添加</a>
 <a class="easyui-linkbutton" iconcls="icon-edit" onclick="edit();">修改</a>
 <a class="easyui-linkbutton" iconcls="icon-remove" onclick="del();">删除</a>
 </div>
 <div>
 <input id="queryBox" class="easyui-textbox" buttonicon="icon-search" style="width: 200px;"
  data-options="onClickButton:function(){loadList(loadListSettings);}" />
 <a class="easyui-linkbutton" iconcls="icon-find" onclick="showQueryWindow();">
  详细查询</a>
 </div>
</div>
<script type="text/javascript">
 var loadListSettings = { searchFields: "customerId,companyName", prompt: "请输入客户Id或公司名称" };
</script>
<script type="text/javascript">
 pageInit();
</script>

为了这样简洁的前台,我们需要准备:

1、通用的布局模板_Layout.cshtml。base.css、base.js、defaultSettings.js、tool.js和private.js见后面

<!doctype html>
<html>
<head>
 <meta charset="utf-8" />
 <meta name="viewport" content="width=device-width" />
 <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
 <link href='/webResource/easyui/themes/default/easyui.css' rel='stylesheet' type='text/css' />
 <link href='/webResource/easyui/themes/icon.css' rel='stylesheet' type='text/css' />
 <link href='/webResource/base.css' rel='stylesheet' type='text/css' />
 <script src="/webResource/jquery/jquery.min.js" type="text/javascript"></script>
 <script src="/webResource/jquery/json2.js" type="text/javascript"></script>
 <script src="/webResource/easyui/jquery.easyui.min.js" type="text/javascript"></script>
 <script src="/webResource/easyui/locale/easyui-lang-zh_CN.js" type="text/javascript"></script>
 <script src="/webResource/tool.js" type="text/javascript"></script>
 <script src="/webResource/base.js" type="text/javascript"></script>
 <script src="/webResource/defaultSettings.js" type="text/javascript"></script>
 <script src="/webResource/private.js" type="text/javascript"></script>
 @RenderSection("scripts", required: false)
</head>
<body style="width: 100%; height: 100%; margin: 0px;">
 @RenderBody()
</body>
</html>

2、平台样式表base.css

.icon-find
{
 background: url('icons/find.png') no-repeat center center;
}

.datagrid-toolbar div:nth-child(1)
{
 float: left;
 width: 60%;
}
.datagrid-toolbar div:nth-child(2)
{
 margin-left: 60%;
 margin-right: 10px;
 width: auto;
 text-align: right;
}

3、基本方法脚本base.js

//取消自动渲染
$.parser.auto = false;

function pageInit() {

 //改变控件默认值
 $.fn.linkbutton.defaults.plain = true;
 $.fn.datagrid.defaults.fit = true;
 $.fn.datagrid.defaults.fitColumns = true;
 $.fn.datagrid.defaults.pagination = true;

 //显示ajax异常信息
 $(document).ajaxError(function (event, xhr, options, exc) {
 $.messager.alert({ title: '异步请求出错', msg: xhr.responseText, icon: "error" });
 });

 //地址栏传参允许中文
 jQuery(document).ajaxSend(function (event, request, options) {
 options.url = encodeURI(options.url);
 });

 $.parser.parse();
}

function loadList(settings) {
 var settings = $.extend(true, {}, loadListDefaultSettings, settings);

 if ($("#" + settings.gridId).length == 0)
 $.messager.alert({ title: "系统异常", msg: "DataGrid:" + settings.gridId + "不存在!", icon: "error" });

 var quickQueryData = [];
 if ($("#" + settings.queryBoxId).length > 0) {
 var val = $("#" + settings.queryBoxId).textbox("getValue");
 if (settings.searchFields && val) {
  var keys = settings.searchFields.split(',');
  for (i = 0, len = keys.length; i < len; i++) {
  quickQueryData.push({ field: keys[i], method: 'inLike', value: val });
  }
 }
 }

 var queryData = []; //详细查询预留 

 //加载数据
 $("#" + settings.gridId).datagrid("load", { quickQueryData: JSON.stringify(quickQueryData), queryData: JSON.stringify(queryData) });
}

4、基本脚本默认值defaultSettings.js

//查询参数设置
var loadListDefaultSettings = {
 url: "getList",
 gridId: "dataGrid",
 queryWindowId: "queryWindow",
 queryBoxId: "queryBox",
 searchFields: "Name",
 addQueryString: true,
 prompt: "请输入"
};

5、可能需要使用的工具方法tool.js

//判断是否包含地址栏参数
function hasQueryString(key, url) {
 if (typeof (url) == "undefined")
 url = window.location.search;

 var re = new RegExp("[?&]" + key + "=([^\\&]*)", "i");
 var a = re.exec(url);
 if (a == null) return false;
 return true;
}

//获取地址栏参数,如果参数不存在则返回空字符串
function getQueryString(key, url) {
 if (typeof (url) == "undefined")
 url = window.location.search;
 var re = new RegExp("[?&]" + key + "=([^\\&]*)", "i");
 var a = re.exec(url);
 if (a == null) return "";
 return a[1];
}

//将当前地址栏参数加入到url
function addUrlSearch(url) {
 var newParams = [];

 var paramKeys = window.location.search.replace('?', '').split('&');
 for (var i = 0; i < paramKeys.length; i++) {
 var key = paramKeys[i].split('=')[0];
 if (key == "" || key == "_t" || key == "_winid" || key == "isTab")
  continue;
 if (!hasQueryString(key, url))
  newParams.push(paramKeys[i]);
 }

 if (url.indexOf('?') >= 0)
 return url + "&" + newParams.join('&');
 else
 return url + "?" + newParams.join('&');
}

//url增加参数
function addSearch(url, key, value) {
 if (!hasQueryString(key, url)) {
 if (url.indexOf('?') >= 0)
  return url + "&" + key + "=" + value;
 else
  return url + "?" + key + "=" + value;
 }
 else
 return url;
}

//获取数组中对象的某个值,逗号分隔
function getValues(rows, attr) {
 var fieldValues = [];
 for (var i = 0; i < rows.length; i++) {
 if (rows[i] != null)
  fieldValues.push(rows[i][attr]);
 }
 return fieldValues.join(',');
}

6、可能需要使用的私有方法private.js,此文件包含的方法专供base.js使用,开发web时禁止使用

//替换掉Url中的{}参数
function replaceUrl(settings, pty) {
 if (!pty)
 pty = "url";
 if (!settings[pty])
 return;
 var str = settings[pty];
 var guid = "";
 var result = str.replace(/\{[0-9a-zA-Z_]*\}/g, function (e) {
 var key = e.substring(1, e.length - 1);

 if (key == "GUID") {
  if (!guid) {
  $.ajax({
   url: "getGuid",
   type: "post",
   async: false,
   success: function (text, textStatus) {
   guid = text;
   }
  });
  }
  return guid;
 }
 if (hasQueryString(key)) //从地址栏返回
  return getQueryString(key);
 if (settings.currentRow && settings.currentRow[key])//从当前行返回
  return settings.currentRow[key];
 if (settings.paramFrom) { //从指定控件返回
  var ctrl = mini.get(settings.paramFrom);
  if (ctrl == undefined) {
  $.messager.alert({ title: 'UI出错', msg: "Id为" + settings.paramFrom + "的控件不存在!", icon: "error" });
  return;
  }
  else if (ctrl.showCheckBox) {
  return getValues(ctrl.getCheckedNodes(), key);
  }
  else if (ctrl.getSelecteds)
  return getValues(ctrl.getSelecteds(), key);
  else if (ctrl.getValue)
  return ctrl.getValue();
 }

 return e;
 });

 settings[pty] = result;
 return result;
}

//转化为全路径
function changeToFullUrl(settings) {
 var url = settings.url;
 if (url.indexOf('/') == 0 || url.indexOf("http://") == 0 || url.indexOf('?') == 0 || url == "")
 return url;

 currentUrlPathName = window.location.pathname;

 var currentPathNameParts = currentUrlPathName.split('/');
 var pathNameParts = url.split('?')[0].split('/');
 if (currentPathNameParts[currentPathNameParts.length - 1] == "")
 currentPathNameParts.pop(); //去掉一个反斜线
 if (pathNameParts[pathNameParts.length - 1] == "")
 pathNameParts.pop(); //去掉一个反斜线

 var index = currentPathNameParts.length - 1;

 for (var i = 0; i < pathNameParts.length; i++) {
 if (pathNameParts[i] == "..") {
  index = index - 1;
  if (index <= 0) {
  $.messager.alert({ title: "系统异常", msg: "Url错误:" + url + "!", icon: "error" });
return;
  }
  continue;
 }

 if (index < currentPathNameParts.length)
  currentPathNameParts[index] = pathNameParts[i];
 else
  currentPathNameParts.push(pathNameParts[i]);
 index = index + 1;
 }
 var length = currentPathNameParts.length;
 for (var i = index; i < length; i++) {
 currentPathNameParts.pop();
 }

 var result = currentPathNameParts.join('/');

 if (url.indexOf('?') > 0)
 result += url.substring(url.indexOf('?'));

 settings.url = result;
}

我们期望简洁的后台代码,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using formula;
using System.Data;

namespace demo.Areas.basic.Controllers
{
 public class customerController : BaseController
 {
 public JsonResult getList(QueryBuilder qb)
 {
  SqlHelper sqlHelper = new SqlHelper("demo");
  var data = sqlHelper.ExecuteGridData("select *,id=customerId from customer", qb);
  return Json(data);
 }
 }
}

为了这种简洁的代码我们需要:

1、Controller基类BaseController:

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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace formula
{
 public class QueryBuilderBinder : IModelBinder
 {
 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
 {
  var qb = (QueryBuilder)(bindingContext.Model ?? new QueryBuilder());
  var dict = controllerContext.HttpContext.Request.Params;

  var quickQueryList = !string.IsNullOrEmpty(dict["quickQueryData"]) ? JsonHelper.ToList(dict["quickQueryData"]) : new List<Dictionary<string, object>>();
  var queryList = !string.IsNullOrEmpty(dict["queryData"]) ? JsonHelper.ToList(dict["queryData"]) : new List<Dictionary<string, object>>();

  foreach (var dic in quickQueryList)
  {
  var val = dic["value"].ToString();
  if (val == "") continue;
  qb.add(dic["field"].ToString(), dic["method"].ToString(), val, true);
  }

  foreach (var dic in queryList)
  {
  var val = dic["value"].ToString();
  if (val == "") continue;
  qb.add(dic["field"].ToString(), dic["method"].ToString(), val, false);
  } 

  qb.page = !string.IsNullOrEmpty(dict["page"]) ? int.Parse(dict["page"].ToString()) : 1;
  qb.rows = !string.IsNullOrEmpty(dict["rows"]) ? int.Parse(dict["rows"].ToString()) : 10;
  qb.sort = !string.IsNullOrEmpty(dict["sort"]) ? dict["page"].ToString() : "id";
  qb.order = !string.IsNullOrEmpty(dict["order"]) ? dict["order"].ToString() : "desc";

  return qb;

 }
 }
}

4、数据库查询帮助类SqlHelper:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Web;

namespace formula
{
 public class SqlHelper
 {
 #region 构造函数

 public SqlHelper(string connName)
 {
  if (System.Configuration.ConfigurationManager.ConnectionStrings[connName] == null)
  throw new BuessinessException(string.Format("配置文件中不包含数据库连接字符串:{0}", connName));
  this.connName = connName;
  this.connString = System.Configuration.ConfigurationManager.ConnectionStrings[connName].ConnectionString;
 }

 public string connName { get; private set; }
 public string connString { get; private set; }
 public string dbName
 {
  get
  {
  SqlConnection conn = new SqlConnection(connString);
  return conn.Database;
  }
 }

 #endregion

 #region 基本方法

 public object ExecuteScalar(string cmdText)
 {
  using (SqlConnection conn = new SqlConnection(connString))
  {
  conn.Open();
  SqlCommand cmd = new SqlCommand(cmdText, conn);
  return cmd.ExecuteScalar();
  }
 }

 public DataTable ExecuteDataTable(string cmdText)
 {
  using (SqlConnection conn = new SqlConnection(connString))
  {
  DataTable dt = new DataTable();
  SqlDataAdapter apt = new SqlDataAdapter(cmdText, conn);
  apt.Fill(dt);
  return dt;
  }
 }

 public DataTable ExecuteDataTable(string cmdText, int start, int len)
 {
  using (SqlConnection conn = new SqlConnection(connString))
  {
  DataTable dt = new DataTable();
  SqlDataAdapter apt = new SqlDataAdapter(cmdText, conn);
  apt.Fill(start, len, dt);
  return dt;
  }
 }

 public string ExecuteNonQuery(string cmdText)
 {
  using (SqlConnection conn = new SqlConnection(connString))
  {
  conn.Open();
  SqlCommand cmd = new SqlCommand(cmdText, conn);
  return cmd.ExecuteNonQuery().ToString();
  }
 }

 #endregion

 #region 支持查询对象

 public DataTable ExecuteDataTable(string sql, SearchCondition cnd, string orderBy)
 {
  string sqlWhere = " where 1=1" + GetUrlFilterSqlWhere(sql) + cnd.getWhereString(false);
  sql = string.Format("select {0} from ({1}) sourceTable {2} {3}", cnd.fields, sql, sqlWhere, orderBy);
  DataTable dt = this.ExecuteDataTable(sql);
  return dt;
 }

 public Dictionary<string, object> ExecuteGridData(string sql, QueryBuilder qb)
 {
  string sqlWhere = " where 1=1" + GetUrlFilterSqlWhere(sql) + qb.getWhereString(false);

  qb.total = (int)this.ExecuteScalar(string.Format("select count(1) from ({0}) sourceTable {1}", sql, sqlWhere));

  sql = string.Format("select {0} from ({1}) sourceTable {2} {3}", qb.fields, sql, sqlWhere, qb.getOrderByString());
  DataTable dt = ExecuteDataTable(sql, (qb.page - 1) * qb.rows, qb.rows);

  Dictionary<string, object> dic = new Dictionary<string, object>();
  dic.Add("total", qb.total);
  dic.Add("rows", dt);
  return dic;
 }

 #endregion

 #region 私有方法

 private string GetUrlFilterSqlWhere(string sql)
 {
  sql = string.Format("select * from({0}) as dt1 where 1=2", sql);
  var dtField = ExecuteDataTable(sql);

  StringBuilder sb = new StringBuilder();
  foreach (string key in HttpContext.Current.Request.QueryString.Keys)
  {
  if (string.IsNullOrEmpty(key) || key.ToLower() == "id")
   continue;

  if (dtField.Columns.Contains(key))
  {
   string value = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request[key]);
   value = value.Replace(",", "','");
   sb.AppendFormat(" and {0} in ('{1}')", key, value);
  }
  }
  return sb.ToString();
 }

 #endregion

 }
}

5、用于取代返回值JsonResult的NewtonJsonResult:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using System.Data;

namespace formula
{
 public class NewtonJsonResult : JsonResult
 {
 public override void ExecuteResult(ControllerContext context)
 {
  //确认是否用于响应HTTP-Get请求
  if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
  string.Compare(context.HttpContext.Request.HttpMethod, "GET", true) == 0)
  {
  throw new InvalidOperationException("禁止Get请求");
  }

  HttpResponseBase response = context.HttpContext.Response;
  //设置媒体类型和编码方式
  response.ContentType = string.IsNullOrEmpty(this.ContentType) ?
  "application/json" : this.ContentType;
  if (this.ContentEncoding != null)
  {
  response.ContentEncoding = this.ContentEncoding;
  }

  //序列化对象,并写入当前的HttpResponse
  if (null == this.Data) return;

  if (this.Data is string)
  {
  response.Write(Data);
  }
  else if (this.Data is DataRow)
  {
  Dictionary<string, object> dic = new Dictionary<string, object>();
  DataRow row = this.Data as DataRow;
  foreach (DataColumn col in row.Table.Columns)
  {
   dic.Add(col.ColumnName, row[col]);
  }
  response.Write(JsonHelper.ToJson(dic));
  }
  else
  {
  response.Write(JsonHelper.ToJson(this.Data));
  }
 }
 }

}

6、Json序列化和反序列的帮助类JsonHelper:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;

namespace formula
{
 public static class JsonHelper
 {
 public static string ToJson<T>(T obj)
 {

  if (obj == null || obj.ToString() == "null") return null;

  if (obj != null && (obj.GetType() == typeof(String) || obj.GetType() == typeof(string)))
  {
  return obj.ToString();
  }

  IsoDateTimeConverter dt = new IsoDateTimeConverter();
  dt.DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss";
  return JsonConvert.SerializeObject(obj, dt);

 }

 /// <summary>
 /// 从一个Json串生成对象信息
 /// </summary>
 /// <param name="jsonString">JSON字符串</param>
 /// <typeparam name="T">对象类型</typeparam>
 /// <returns></returns>
 public static T ToObject<T>(string json) where T : class
 {
  if (String.IsNullOrEmpty(json)) return null;
  T obj = JsonConvert.DeserializeObject<T>(json);
  return obj;
 }

 /// <summary>
 /// 返回 Diction<string,object>
 /// </summary>
 /// <param name="json"></param>
 /// <returns></returns>
 public static Dictionary<string, object> ToObject(string json)
 {
  if (String.IsNullOrEmpty(json)) return new Dictionary<string, object>();
  return ToObject<Dictionary<string, object>>(json);
 }

 /// <summary>
 /// 返回 List<Dictionary<string, object>>
 /// </summary>
 /// <param name="json"></param>
 /// <returns></returns>
 public static List<Dictionary<string, object>> ToList(string json)
 {
  if (String.IsNullOrEmpty(json)) return new List<Dictionary<string, object>>();
  return ToObject<List<Dictionary<string, object>>>(json);
 }

 /// <summary>
 /// 组装对象
 /// </summary>
 /// <param name="json"></param>
 /// <param name="obj"></param>
 public static void PopulateObject(string json, object obj)
 {
  if (String.IsNullOrEmpty(json)) return;
  JsonConvert.PopulateObject(json, obj);
 }
 }
}

7、用于区分系统异常和业务异常的BusinessException:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace formula
{
 /// <summary>
 /// 业务异常
 /// </summary>
 [Serializable]
 public class BuessinessException : Exception
 {
 /// <summary>
 /// 系统异常构造函数
 /// </summary>
 public BuessinessException()
 {

 }

 /// <summary>
 /// 系统异常构造函数
 /// </summary>
 /// <param name="message">异常的消息</param>
 public BuessinessException(string message)
  : base(message)
 {

 }

 /// <summary>
 /// 系统异常构造函数
 /// </summary>
 /// <param name="message">异常的消息</param>
 /// <param name="inner">内部的异常</param>
 public BuessinessException(string message, System.Exception inner)
  : base(message, inner)
 {

 }

 /// <summary>
 /// 系统异常构造函数
 /// </summary>
 /// <param name="info">存有有关所引发异常的序列化的对象数据</param>
 /// <param name="context">包含有关源或目标的上下文信息</param>
 public BuessinessException(SerializationInfo info, StreamingContext context)
  : base(info, context)
 {

 }
 }
}

最后,上代码:http://xiazai.jb51.net/201604/yuanma/ASP.NET-MVC-EasyUI-sampleFrame%28jb51.net%29.rar

(0)

相关推荐

  • 使用jQuery向asp.net Mvc传递复杂json数据-ModelBinder篇

    调用jQuery的ajax方法时,jQuery会根据post或者get协议对参数data进行序列化; 如果提交的数据使用复杂的json数据,例如: {userId:32323,userName:{firstName:"李",lastName:"李大嘴"}} 那么服务器是无法正常接收到完整的参数,因为jQuery对data的序列化,是使用了键值对拼装的方式; 参数拼装成 userId=32323&userName=object ; userName所指向的对象

  • ASP.NET MVC DropDownList数据绑定及使用详解

    一:DropDownList 1.1 DropDownList绑定数据 1.1.1 DropDownList 固定绑定 这种方式适合那些已经固定的数据绑定到DropDownList上. 例 复制代码 代码如下: <asp:DropDownList runat="server" ID="ddlArea" Width="120px" > <asp:Listitem value="0">选择性别</as

  • asp.net实现的MVC跨数据库多表联合动态条件查询功能示例

    本文实例讲述了asp.net实现的MVC跨数据库多表联合动态条件查询功能.分享给大家供大家参考,具体如下: 一.控制器中方法 [HttpGet] public ActionResult Search() { ViewBag.HeadTitle = "搜索"; ViewBag.MetaKey = "\"123\""; ViewBag.MetaDes = "\"456\""; string whereText

  • ASP.NET中MVC从后台控制器传递数据到前台视图的方式

    本文实例讲述了ASP.NET中MVC从后台控制器传递数据到前台视图的方式.分享给大家供大家参考.具体分析如下: 数据存储模型Model: 复制代码 代码如下: public class CalendarEvent { public string id { get; set; } public DateTime start { get; set; } public DateTime end { get; set; } public string backgroundColor { get; set

  • Asp.net mvc 数据调用示例代码

    (1)首先我们创建一个mvc项目,当然最好是mvc1.0版本以上. (2)我这个小Demo,没有重新配置路由解析,使用的是mvc项目默认的路由解析地址.当然如果谁感兴趣也可以自己添加一个默认路由! (3)我这里有一个名字叫Database1.mdf的数据库,里面包含一个News表. (4)然后我们右击Models文件夹,Models>添加新项,选择: 名字可以自己随便起.我这里叫做Test.edmx,然后点击添加. 下一步: 这里我们可以点击新建连接,来选择自己想要的数据库,最下面的是WebCo

  • ASP.NET Mvc开发之删除修改数据

    之前那篇文章介绍了ASP.NET MVC使用EF来查询数据和EF中DbQuery<T>泛型对象对数据的延迟加载.今天我们就来看看我们怎么使用EF来删除数据. 其实现在的Web开发通用的模式就是前端使用Js和JQuery来和后端进行数据交互.那么我们就在前端来加两个删除和更新的脚本.代码如下: <!--遍历 Action方法 设置给 ViewData 的集合数据,生成HTML代码--> @foreach (BlogArticle a in ViewData["DataLis

  • ASP.NET Mvc开发之查询数据

    对于.NET平台上开发WebForm项目,程序员操作数据的方法主要是通过使用ADO.NET.而我们MVC操作数据库呢?与ADO.NET相比又有怎样的优势呢? 一.大家都在谈的EF到底是什么? EF,全称EntityFramWork.就是微软以ADO.NET为基础发展的所谓ORM(对象关系映射框架,或者说是数据持久化框架). 简单的来说就是根据实体对象操作数据表中数据的一种面向对象的操作框架,具体的底层也是调用ADO.NET. 下面我们就来演示怎么使用EF来操作数据库: 在数据库关系图中,表之间的

  • asp.net mvc 从数据库中读取图片的实现代码

    首先是创建一个类,继承于ActionResult,记住要引用System.Web.Mvc命名空间,如下: 复制代码 代码如下: public class ImageResult : ActionResult { public ImageFormat ContentType { get; set; } public Image image { get; set; } public string SourceName { get; set; } public ImageResult(string _

  • ASP.NET MVC 数据验证及相关内容

    一.数据验证 数据验证的步骤在模型类中添加与验证相关的特性标记在客户端导入与验证相关的js文件和css文件使用与验证相关的Html辅助方法在服务器端判断是否通过服务器端验证常用的验证标记 Required:非空验证StringLength:验证字符串的长度RegularExpression:正则表达式验证Compare:比较两个字段的值是否相等Range:范围验证Remote:服务器验证(需要在controller中编写返回值为JsonResult的Action)自定义验证标记与验证相关的js文

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

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

  • JQuery对ASP.NET MVC数据进行更新删除

    以前学习ASP.NET MVC时,学习与应用,操作过数据显示,添加,编辑,更新和删除等功能. 很多方法是相通的,看自己是怎样来进行方便,快捷,高效率. 今天Insus.NET写的练习,是直接对绑定在Table的数据进行更新,删除. 在项目中,创建一个实体,也就是说,对数据库时行通信,对数据进行操作: public IEnumerable<ToolLocation> GetAllToolLocations() { sp.ConnectionString = DB.ConnectionString

  • asp.net mvc4 mysql制作简单分页组件(部分视图)

    在开始做mysql分页功能组件前,便设定的是要有一定可复用性.先在项目里Views文件夹下右键新建名为_PaginationComponent.cshtml,这里html及css我采用的bootstrap分页组件,这可以参考http://v3.bootcss.com/components/. 先将生成项目效果截图呈上: 这里有需要预先知道的,是mysql分页查询与mssql分页查询实现不同点在于,mysql支持limit语句,limit格式为 limit pageIndex*pageSize,p

  • ASP.NET中MVC传递数据的几种形式总结

    本文实例讲述了ASP.NET中MVC传递数据的几种形式.分享给大家供大家参考.具体如下: 在Asp.net mvc开发中,Controller需要向View提供Model,然后View将此Model渲染成HTML.这篇文章介绍三种由Controller向View传递数据的方式,实现一个DropDownList的显示. 第一种:ViewData ViewData是一个Dictionary.使用非常简单,看下面代码: public ActionResult ViewDataWay(int id) {

随机推荐