基於MVC4+EasyUI的Web開發架構形成之旅--MVC控制器的設計

來源:互聯網
上載者:User

標籤:web開發   mvc   easyui   web開發架構   

自從上篇《基於MVC4+EasyUI的Web開發架構形成之旅--總體介紹》總體性的概括,得到很多同行的關注和支援,不過上一篇主要是介紹一個總體的介面效果和思路,本系列的文章將逐步介紹其中的細節,本文主要介紹整個Web開發架構中的MVC控制器的設計。在設計之初,我就希望儘可能的減少代碼,提高編程模型的統一性。因此希望能夠以基類繼承的方式,和我Winform開發架構一樣,儘可能通過基類,而不是子類的重複代碼來實現各種通用的操作。

1、登入控制的控制器基類設計

我們知道,一般我們建立一個MVC的控制器,都是基於Controller這樣的基類來實現。如下代碼所示。

650) this.width=650;" src="http://images.cnitblog.com/blog/8867/201308/27113133-e3f253b26ef64041a3781e1747481c3e.png" style="border:0px;" />

public class TestController : Controller{//// GET: /Test/public ActionResult Index(){return View();}}

在我的Winform開發架構裡面,用到了泛型的類型,非常方便實現商務邏輯和資料訪問基類的設計,控制器是否也可以這樣做的呢?

我們知道,一般的MVC控制器需要驗證使用者是否已經登陸了,這也是很多常見Web操作前的驗證,還有對異常的處理,在MVC的基類,可以一併進行記錄(這個非常不錯),於是我們先來設計一個驗證使用者身份是否登陸的基類BaseController

/// <summary>/// 所有需要進行登入控制的控制器基類/// </summary>public class BaseController : Controller {/// <summary>/// 當前登入的使用者屬性/// </summary>public UserInfo CurrentUserInfo { get; set; }/// <summary>/// 重新基類在Action執行之前的事情/// </summary>/// <param name="filterContext">重寫方法的參數</param>protected override void OnActionExecuting(ActionExecutingContext filterContext){base.OnActionExecuting(filterContext);//得到使用者登入的資訊CurrentUserInfo = Session["UserInfo"] as UserInfo;//判斷使用者是否為空白if (CurrentUserInfo == null){Response.Redirect("/Login/Index");}}protected override void OnException(ExceptionContext filterContext){base.OnException(filterContext);//錯誤記錄WHC.Framework.Commons.LogTextHelper.Error(filterContext.Exception);// 當自訂顯示錯誤 mode = On,顯示友好錯誤頁面if (filterContext.HttpContext.IsCustomErrorEnabled){filterContext.ExceptionHandled = true;this.View("Error").ExecuteResult(this.ControllerContext);}}........................}

有了這個基類,我們在首頁的Home控制類,就可以使用使用者資訊對象了進行操作了,而且必須要求客戶登陸了。

public class HomeController : BaseController{public ActionResult Index(){if (CurrentUserInfo != null){ViewBag.FullName = CurrentUserInfo.FullName;ViewBag.Name = CurrentUserInfo.Name;}return View();}................}

 

2、資料訪問業務基類控制器的設計

我在我的Winform開發架構裡面,對很多基類都使用泛型進行設計,這樣可以傳遞相應的資料類型到基類裡面進行處理,如下面的BLL層的業務對象定義代碼如下所示。

namespace WHC.Security.BLL{    /// <summary>    /// 角色資訊業務管理類    /// </summary>    public class Role : BaseBLL<RoleInfo>    {....................
/// <summary>/// 業務基類對象/// </summary>/// <typeparam name="T">業務物件類型</typeparam>public class BaseBLL<T> where T : BaseEntity, new(){/// <summary>/// 插入指定對象到資料庫中/// </summary>/// <param name="obj">指定的對象</param>/// <returns>執行操作是否成功。</returns>public virtual bool Insert(T obj){return baseDal.Insert(obj);}............

業務對象Role,要求傳入RoleInfo給基類處理,這樣基類就能定義到都對應的T為具體的RoleInfo類型了。在MVC的控制器是否也可以這樣做呢?當然可以,下面是我定義的一個控制器繼承關係圖。

650) this.width=650;" src="http://images.cnitblog.com/blog/8867/201308/27120607-6ad84bc6809c4e0fa5d46150569ce385.png" style="border:0px;" />

上面的介紹也已經比較明白了,其實就是在BusinessController<B, T>裡面傳入了兩個參數,定義代碼如下所示。

/// <summary>/// 本控制器基類專門為訪問資料業務對象而設的基類/// </summary>/// <typeparam name="B">業務物件類型</typeparam>/// <typeparam name="T">實體類類型</typeparam>public class BusinessController<B, T> : BaseControllerwhere B : classwhere T : WHC.Framework.ControlUtil.BaseEntity, new(){/// <summary>/// 插入指定對象到資料庫中/// </summary>/// <param name="info">指定的對象</param>/// <returns>執行操作是否成功。</returns>public virtual ActionResult Insert(T info){bool result = false;if (info != null){result = baseBLL.Insert(info);}return Content(result);}................

我根據傳入的BLL業務物件類型B,對象實體類類型T,那麼我們就可以構造對應的baseBLL對象,然後調用其基類介面實現基本的操作,如插入,刪除,更新,尋找等等,這樣的模式就和我的Winform開發架構的理念非常吻合了。

我們以角色控制器來說明,它的定義如下所示,如果不需要實現額外的介面(除了常見的操作),基本上不需要寫任何代碼了,因為所有很多常見的操作,都已經封裝在了基類控制器BusinessController<B, T>裡面了。

/// <summary>/// 角色業務操作控制器/// </summary>public class RoleController : BusinessController<Role, RoleInfo>{public RoleController() : base(){}...............

對於一些需要特殊資料處理的操作,可以增加一些自訂的介面函數,也可以重寫基類的一些介面,實現資料的相應處理。如我的菜單介面顯示中,需要根據縮排的層級對菜單名稱進行縮排,以便更好的展示它們的層級結構,那麼我就需要對分頁函數進行重寫了,如下代碼所示是整個菜單Menu類的控制器類代碼。

public class MenuController : BusinessController<Menu, MenuInfo>{public override ActionResult FindWithPager(){string where = GetPagerCondition(); //基類實現PagerInfo pagerInfo = GetPagerInfo(); //基類實現            List<MenuInfo> list = baseBLL.FindWithPager(where, pagerInfo);list = CollectionHelper<MenuInfo>.Fill("-1", 0, list, "PID", "ID", "Name");//Json格式的要求{total:22,rows:{}}//構造成Json的格式傳遞var result = new { total = pagerInfo.RecordCount, rows = list };return JsonDate(result);}/// <summary>/// 用作下拉式清單的菜單Json資料/// </summary>/// <returns></returns>public ActionResult GetDictJson(){List<MenuInfo> list = baseBLL.GetAll();list = CollectionHelper<MenuInfo>.Fill("-1", 0, list, "PID", "ID", "Name");List<CListItem> itemList = new List<CListItem>();foreach (MenuInfo info in list){itemList.Add(new CListItem(info.Name, info.ID));}return Json(itemList, JsonRequestBehavior.AllowGet);}}

 

我們來看看一段HTML頁面裡面,使用javascript指令碼調用控制器API來實現資料的綁定的操作,也就是使用樣本。

$.getJSON("/Role/FindById?r=" + Math.random() + "&id=" + id, function (json) {$("#txtID").val(json.ID);$("#txtName").val(json.Name);$("#txtNote").val(json.Note);});

上面這個很標準的介面FindById是業務基類控制器BusinessController<B, T>裡提供的。

當然,BusinessController裡面可以類似我Winform開發架構裡面基類一樣,提供很豐富的操作介面,如返回列表Json集合,增刪改查的操作及返回,分頁資料的返回,以及一些特殊的操作都可以實現。而這些都不需要子類進行任何實現。

如下面實際案例的使用者登陸日誌,裡面的介面功能還是很豐富的,當他的控制器業務類不需要任何實現,只需要繼承基類即可。

650) this.width=650;" src="http://images.cnitblog.com/blog/8867/201308/27122418-13971a0ef88645eb847ae14de71ad986.png" style="border:0px;" />

    public class LoginLogController : BusinessController<LoginLog, LoginLogInfo>    {        public LoginLogController() : base()        {        }    }

介面部分代碼如下所示。

//實現對DataGird控制項的綁定操作function InitGrid(queryData) {$(‘#grid‘).datagrid({   //定位到Table標籤,Table標籤的ID是gridurl: ‘/LoginLog/FindWithPager‘,   //指向背景Action來擷取目前使用者的資訊的Json格式的資料title: ‘使用者登陸日誌‘, //下面的這些屬性如果誰不太清楚的話我建議去官方網站去學習iconCls: ‘icon-view‘,height: 450,nowrap: true,autoRowHeight: false,striped: true,collapsible: true,pagination: true,rownumbers: true,//sortName: ‘ID‘,    //根據某個欄位給easyUI排序sortOrder: ‘asc‘,remoteSort: false,idField: ‘ID‘,queryParams: queryData,  //非同步查詢的參數columns: [[{ field: ‘ck‘, checkbox: true },   //選擇{ title: ‘ID‘, field: ‘ID‘, width: 40, sortable: true },  //主鍵 { title: ‘登入使用者ID‘, field: ‘User_ID‘, width: 80, sortable: true }, { title: ‘登入名稱稱‘, field: ‘LoginName‘, width: 80, sortable: true }, { title: ‘真實名稱‘, field: ‘FullName‘, width: 80, sortable: true }, { title: ‘日誌描述‘, field: ‘Note‘, width: 100, sortable: true }, { title: ‘IP地址‘, field: ‘IPAddress‘, width: 100, sortable: true }, { title: ‘Mac地址‘, field: ‘MacAddress‘, width: 120, sortable: true }, { title: ‘系統編號‘, field: ‘SystemType_ID‘, width: 120, sortable: true }, { title: ‘記錄日期‘, field: ‘LastUpdated‘, width: 120, sortable: true },]],toolbar: [{id: ‘btnAdd‘,text: ‘添加‘,iconCls: ‘icon-add‘,handler: function () {                        ShowAddDialog();//實現添加記錄的頁面}}, ‘-‘, {id: ‘btnEdit‘,text: ‘修改‘,iconCls: ‘icon-edit‘,handler: function () {                        ShowEditOrViewDialog();//實現修改記錄的方法}}, ‘-‘, {id: ‘btnDelete‘,text: ‘刪除‘,iconCls: ‘icon-remove‘,handler: function () {                        Delete();//實現直接刪除資料的方法}}, ‘-‘, {id: ‘btnView‘,text: ‘查看‘,iconCls: ‘icon-table‘,handler: function () {                        ShowEditOrViewDialog("view");//實現查看記錄詳細資料的方法}}, ‘-‘, {id: ‘btnReload‘,text: ‘重新整理‘,iconCls: ‘icon-reload‘,handler: function () {//實現重新整理欄目中的資料$("#grid").datagrid("reload");}}]});$(‘#grid‘).datagrid({onDblClickRow: function (rowIndex, rowData) {$(‘#grid‘).datagrid(‘uncheckAll‘);$(‘#grid‘).datagrid(‘checkRow‘, rowIndex);ShowEditOrViewDialog();}});}

這個就是我的控制器設計的中心思想了,下一篇繼續介紹整體的MVC系列的Web開發架構,介紹其中Web介面部分的處理和相關經驗,希望大家多多提出寶貴的意見。

本文出自 “伍華聰的部落格” 部落格,請務必保留此出處http://wuhuacong.blog.51cto.com/1779896/1828902

基於MVC4+EasyUI的Web開發架構形成之旅--MVC控制器的設計

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.