Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use ASP.NET MVC+EasyUI+SqlServer to build Enterprise Development Framework

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to use ASP.NET MVC+EasyUI+SqlServer to build an enterprise development framework. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

The framework we want to build is an enterprise development framework, which is suitable for the development of enterprise management information systems, such as OA, HR, etc.

1. Frame name: sampleFrame.

2. the principle of building: the principle of least knowledge.

3. Define a simple coding specification: except for the class name and interface name, the rest of the initials are lowercase.

4. Prepare the development environment: vs2010 and above (mvc4), sqlserver, jquery2.0 and easyui1.4.5

First, let's take a look at the effect diagram of the list page:

We expect to be concise with foreground code, as follows:

CustomerId companyName phone address modify detailed query var loadListSettings = {searchFields: "customerId,companyName", prompt: "Please enter customer Id or company name"}; pageInit ()

For such a simple receptionist, we need to prepare:

1. General layout template _ Layout.cshtml. Base.css, base.js, defaultSettings.js, tool.js and private.js see later

RenderSection ("scripts", required: false) @ RenderBody ()

2. Platform style sheet 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. Basic method script base.js

/ / cancel automatic rendering $.parser.auto = false;function pageInit () {/ / change the default value of the control $.fn.linkbutton.defaults.plain = true; $.fn.datagrid.defaults.fit = true; $.fn.datagrid.defaults.fitColumns = true; $.fn.datagrid.defaults.pagination = true / / display ajax exception information $(document) .ajaxError (function (event, xhr, options, exc) {$.messager.alert ({title: 'asynchronous request error', msg: xhr.responseText, icon: "error"}); / / address bar parameters allow Chinese 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: "system exception", msg: "DataGrid:" + settings.gridId + "does not exist!" , 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];}//将当前地址栏参数加入到urlfunction 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 increase the parameter 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 } / / get a value of an object in the array, separated by commas: function getValues (rows, attr) {var fieldValues = []; for (var I = 0; I < rows.length; iTunes +) {if (rows [I]! = null) fieldValues.push (rows [I] [attr]);} return fieldValues.join (',');}

6. Private method private.js that you may need to use. The method contained in this file is designed for base.js and is prohibited when developing web.

/ / replace the {} parameter function replaceUrl (settings, pty) {if (! pty) pty = "url" in Url; if (! settings [pty]) return; var str = settings [pty]; var guid = ""; var result = str.replace (/\ {[0-9aMurzAmurz _] *\} / 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)) / / returns return getQueryString (key) from the address bar; if (settings.currentRow & & settings.currentRow [key]) / / returns return settings.currentRow [key] from the current line If (settings.paramFrom) {/ / returns var ctrl = mini.get (settings.paramFrom) from the specified control; if (ctrl = = undefined) {$.messager.alert ({title:'UI error', msg: "the control with Id" + settings.paramFrom + "does not exist!" , 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;} / / convert to full-path 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 () / remove a backslash if (pathNameParts [pathNameParts.length-1] = ") pathNameParts.pop (); / remove a backslash var index = currentPathNameParts.length-1; for (var I = 0; I < pathNameParts.length; ionization +) {if (pathNameParts [I] =".. ") {index = index-1; if (index 0) result + = url.substring (url.indexOf ('?)); settings.url = result;}

We expect a concise background code, as follows:

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

For this concise code, we need to:

1. Controller base class 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 handles non-existent Action protected override void HandleUnknownAction (string actionName) {if (Request.HttpMethod = = "POST") {HttpContext.ClearError (); HttpContext.Response.Clear () HttpContext.Response.StatusCode = 500; HttpContext.Response.Write ("No Action:" + actionName); HttpContext.Response.End ();} / / search whether the file exists 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 ("No Action:" + actionName); HttpContext.Response.End () } # endregion # region base class Json method overloads 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 exception handling 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. Query constructor 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; iTunes +) {str + = sortFields [I] + "+ sortOrders [I] +", ";} if (hasOrderBy & & str! =") str = "order by" + str; return str.Trim (',');} public class SearchCondition {public string fields = "*"; private List quickItems = new List (); private List complexItems = new List () Public SearchCondition add (string field, string method, object val, bool isQuickSearch = false) {/ / processing date data if (method = = "

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report