Design of--MVC Controller for the formation of web development framework based on Mvc4+easyui

Source: Internet
Author: User

Http://www.cnblogs.com/wuhuacong/p/3284628.html

Since the last chapter of the "Web development framework based on MVC4+EASYUI-General introduction," The overall summary of the general, get a lot of peer attention and support, but the previous one is mainly to introduce an overall interface effect and ideas, this series of articles will gradually introduce the details of it, This paper mainly introduces the design of MVC controller in the whole Web development framework. At the beginning of the design, I wanted to reduce the code as much as possible and improve the consistency of the programming model. Therefore, I want to be able to inherit from the base class, and I WinForm development Framework, as far as possible through the base class, rather than the subclass of duplicate code to achieve a variety of common operations.

1, Login control of the controller base class design

We know that in general we create an MVC controller that is based on a base class such as Controller. As shown in the following code.

    public class Testcontroller:controller    {        ////        GET:/test/public        actionresult Index ()        {            return View ();        }    }

In my WinForm development framework, using the generic type, it is very convenient to implement the business logic and data access base class design, whether the controller can do this?

We know that the general MVC controller needs to verify that the user has landed, this is also a lot of common web operations before the validation, and the exception of the processing, in the MVC base class, can be recorded together (this is very good), So let's start by designing a base class to verify that the user's identity is logged in Basecontroller

    <summary>////For all controller base classes that require login control////</summary> public class Basecontroller:controller { <summary>///user properties for current login///</summary> public UserInfo currentuserinfo {get; Set }///<summary>//re-base class before action executes///</summary>//<param name= "Filterco        ntext "> override method Parameters </param> protected override void OnActionExecuting (ActionExecutingContext filtercontext) {base.            OnActionExecuting (Filtercontext);            Get user login Information Currentuserinfo = session["UserInfo"] as UserInfo;            Determines whether the user is empty if (Currentuserinfo = = null) {Response.Redirect ("/login/index"); }} protected override void Onexception (Exceptioncontext filtercontext) {base.            Onexception (Filtercontext); Error logging WHC.Framework.Commons.LogTextHelper.Error (filtercontext.exceptION);                When the custom display error mode = ON, the friendly error page is displayed if (filterContext.HttpContext.IsCustomErrorEnabled) {                Filtercontext.exceptionhandled = true; This. View ("Error"). Executeresult (this.            ControllerContext); }        }
........................ }

With this base class, we can use the user information object to operate the home control class on the homepage, and must ask the customer to log in.

    public class Homecontroller:basecontroller    {public        actionresult Index ()        {            if (currentuserinfo! = NULL)            {                viewbag.fullname = currentuserinfo.fullname;                Viewbag.name = Currentuserinfo.name;            }            return View ();        } ................    }

2. Design of base class controller for data access service

In my WinForm development framework, many base classes are designed with generics so that the corresponding data types can be passed to the base class for processing, as shown below in the business object definition code for the BLL layer below.

Namespace WHC. security.bll{//<summary>///    role Information Business Management///    </summary> public    class role:basebll< roleinfo> {.............    
    <summary>///    Business base class objects///</summary>//    <typeparam name= "T" > Business object Type </typeparam > Public    class basebll<t> where t:baseentity, new () {///        <summary>//        Insert the specified object into the database///</summary>//        <param name= "obj" > Specified objects </param>//        <returns > succeeded in executing the operation. </returns> public        virtual bool Insert (T obj)        {            return basedal.insert (obj);        } ............

The business object role, which requires that the Roleinfo be passed to the base class, so that the base class can be defined to correspond t to the specific roleinfo type. Can the MVC controller also do this? Of course, here is a controller inheritance diagram that I have defined.

The above introduction has also been relatively clear, in fact, in Businesscontroller<b, t> inside passed two parameters, the definition code is as follows.

    <summary>////    The base class of this controller is specifically designed to access data business objects///</summary>//    <typeparam name= "B" > Business object Type </typeparam>//    <typeparam name= "T" > Entity class type </typeparam> public    class Businesscontroller<b, t>: Basecontroller        where B:class        where T:WHC. Framework.ControlUtil.BaseEntity, New () {///<summary>/////        </summary Insert the specified object into the database        >//        <param name= "INFO" > Specified objects </param>//        <returns> Whether the operation was successful. </returns> public        virtual ActionResult Insert (T info)        {            bool result = false;            if (info! = null)            {                result = Basebll.insert (info);            }            return Content (result);        } ................

I am based on an incoming BLL business object Type B, Object entity class type T, then we can construct the corresponding BASEBLL object and then call its base class interface to implement basic operations such as INSERT, delete, update, find, etc., this pattern is very consistent with the concept of my WinForm development framework.

We use the role controller to illustrate, it is defined as follows, if you do not need to implement additional interfaces (except for common operations), there is basically no need to write any code, because all the common operations are already encapsulated in the base class controller businesscontroller<b, t> It's inside.

    <summary>///    Role Business Operations Controller///    </summary> public    class Rolecontroller:businesscontroller <role, roleinfo>    {public        Rolecontroller (): Base ()        {        } ......

For some operations that require special data processing, you can add some custom interface functions, or you can override some interfaces of the base class to implement the corresponding processing of the data. As my menu interface displays, I need to indent the menu names according to the level of indentation to better show their hierarchies, so I need to rewrite the paging function, as shown in the code for the Controller class of the menu class.

public class Menucontroller:businesscontroller<menu, menuinfo> {publicOverride ActionResult Findwithpager () {String where = Getpagercondition ();//base class implementation Pagerinfo Pagerinf o = Getpagerinfo ();            Base class implementation List<menuinfo> List = Basebll.findwithpager (where, pagerinfo); list = Collectionhelper<menuinfo>.            Fill ("1", 0, List, "PID", "ID", "Name"); JSON format requirements {total:22,rows:{}}//Constructed in JSON format passed var result = new {total = Pagerinfo.recordcount, rows            = list};        return jsondate (Result); }///<summary>///Use as menu JSON data for drop-down list///</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); }    }

Let's take a look at an HTML page that uses JavaScript scripts to invoke the Controller API to implement data binding operations, that is, using the example.

            $.getjson ("/role/findbyid?r=" + math.random () + "&id=" + ID, function (JSON) {                $ ("#txtID"). Val (json.id);                $ ("#txtName"). Val (JSON. Name);                $ ("#txtNote"). Val (JSON. (Note);            });

Above this very standard interface FindByID is the business base class controller businesscontroller<b, T> provided.

Of course, Businesscontroller inside can be similar to my WinForm framework inside the base class, provide a very rich operation interface, such as the return list JSON collection, delete and change the operation and return, paging data return, as well as some special operations can be achieved. These do not require any implementations of subclasses.

As the actual case of the user login log, the interface function is very rich, when his controller business class does not need any implementation, only need to inherit the base class.

    public class Loginlogcontroller:businesscontroller<loginlog, loginloginfo>    {        public Loginlogcontroller (): Base ()        {        }    }

The interface section code is shown below.

        Implements the bind operation to the Datagird control function Initgrid (querydata) {$ (' #grid '). DataGrid ({//Navigate to Table label, table label The ID is the grid URL: '/loginlog/findwithpager ',//The data that points to the background of the action to get the current user's information in JSON format title: ' User log '                ,///below these properties if anyone is not sure, I suggest going to the official website to learn iconcls: ' Icon-view ', height:450,                Nowrap:true, Autorowheight:false, Striped:true, Collapsible:true,                Pagination:true, Rownumbers:true,//sortname: ' ID ',//Sort Easyui according to a field SortOrder: ' ASC ', Remotesort:false, IDfield: ' ID ', Queryparams:                    Querydata,//parameters of the asynchronous query columns: [[{field: ' CK ', checkbox:true},//Select {title: ' id ', field: ' ID ', width:40, sortable:true},//primary key {title: ' Login User ID ', field: ' User_ID ', width:80, sortable:True}, {title: ' Login name ', field: ' LoginName ', width:80, sortable:true}, {title: ' Real name ', field: ' FullName ', width:80, sortable:true}, {title: ' Log description ', field: ' Note ', width:100, S                     Ortable:true}, {title: ' IP Address ', field: ' IPAddress ', width:100, sortable:true}, {title: ' MAC address ', field: ' MacAddress ', width:120, sortable:true}, {title: ' System Number ', field: ' Systems Type_id ', width:120, sortable:true}, {title: ' Record Date ', field: ' LastUpdated ', width:120, sortable:t                    Rue},]], toolbar: [{id: ' Btnadd ', Text: ' Add ',                                                Iconcls: ' Icon-add ', handler:function () {                    Showadddialog ();//Implement Add Record page}}, '-', {ID: ' Btnedit ',      Text: ' Modify ',              Iconcls: ' Icon-edit ', handler:function () {                    Showeditorviewdialog ();//Implement modify Record Method}}, '-', {ID: ' Btndelete ',                                                Text: ' Delete ', iconcls: ' Icon-remove ', handler:function () {                    Delete ();//Implement the method of deleting data directly}}, '-', { ID: ' Btnview ', text: ' View ', Iconcls: ' icon-table ', handler:f                    Unction () {Showeditorviewdialog ("view");//Implement a way to view the details of a record }}, '-', {ID: ' btnreload ', text: ' Refresh ', iconcls : ' Icon-reload ', handler:function () {//implementation refreshes the data in the column $ ("# Grid "). DataGrid (" Reload ").);            }                }]            }); $ (' #grid '). DataGrid ({ondblclickrow:function (RowIndex, RowData) {$ (' #grid '). DataGrid (                    ' Uncheckall ');                    $ (' #grid '). DataGrid (' Checkrow ', rowIndex);                Showeditorviewdialog ();        }            }); }

This is the main idea of my controller design, the next article continues to introduce the whole MVC series of web development Framework, the Web interface part of the processing and related experience, I hope that we have a lot of valuable comments.

(RPM) Design of Mvc4+easyui-based Web development Framework--MVC Controller

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.