Using dynamic and ExpandoObject in the MVC controller to achieve data escaping output

Source: Internet
Author: User

In many cases, we define the table field in the database and the actual content displayed on the page, often is not very matching, the page data may be multiple table data complex, so in addition to our design in the form of thoughtful, but also to consider the data presentation processing. In the case of regular processing, there is a need for special escapes for some foreign key fields, which can be relatively cumbersome if you need to add more fields. This article describes how to use dynamic and ExpandoObject in an MVC controller to achieve an integrated output after data escaping, including adding any number of field information.

1, the display of data information

In general, the information we display in the interface is relatively rich, although when we design the data table, we consider how to simplify and avoid duplication, but the information displayed on the interface is often about how to make the user more convenient, so it is possible to display relevant information as much as possible.

For such a scenario, the device information as the main basic information, its related business including equipment inspection, equipment maintenance, equipment repair and other information, as shown below.

Based on the above data design, if we display equipment inspection, equipment maintenance, equipment repair and other information, then we generally also need to show some of the device basic information, so that we can more easily understand the entire record data, but we are in the design of the data is to separate them, so we need to output to the interface, Combine them.

I used to summarize the experience of the Web development framework based on MVC4+EASYUI (9)--the escape operation of implementing a foreign key field in the DataGrid has introduced some data escaping processing, but that is not the ideal way. This article describes the use of dynamic and expandoobject is my ideal processing mode.

Let's take a look at the interface effects I've finally implemented in this way, and then we'll step through how to implement the process.

2. Implementation of data escaping

In the above interface effect, we are based on the MVC implementation of the background processing, the interface with the use of bootstrap to display (using the Eaysui component is similar to processing). We are divided into two parts for implementation, part of the output data using MVC, part of the interface display.

1) MVC's Controller data processing

In MVC, we generally use the base class Findwithpager to do data paging, based on how to implement data paging in the MVC controller, we are interested to refer to the Metronic-based Bootstrap development Framework Experience Summary (2)--list page processing and plug-in jstree use of the essay to understand.

As a general practice, if it is the main table information, we can put them in a simple output, as shown below.

         Public OverrideActionResult Findwithpager () {//Check whether the user has permission or throw mydenyaccessexception exception            Base.            Checkauthorized (Authorizekey.listkey); string where=getpagercondition (); Pagerinfo Pagerinfo=Getpagerinfo (); List<DeviceInfo> list = Basebll.findwithpager (where, Pagerinfo); //JSON-formatted requirements {total:22,rows:{}}//structure to JSON format delivery            varresult =New{total = pagerinfo.recordcount, rows =list}; returntojsoncontentdate (Result); }

That is, you do not need to pass any escape to direct the query to the data list to the caller, the interface for data filtering processing.

If the above mentioned equipment inspection, equipment repair and equipment information related, we need to use dynamic and ExpandoObject, the device information is integrated together to provide the interface, the specific code is as follows.

We first iterate over the records of the query and convert each record, as shown below.

            New List<expandoobject>();             foreach inch list)            {                dynamicnew ExpandoObject ();

Note that we have defined the list of list<expandoobject> and the object of dynamic obj so that we can add the field properties we need to the dynamic object by dynamically defining the object, and then put it inside the collection.

The full paging controller code is shown below.

         Public OverrideActionResult Findwithpager () {//Check whether the user has permission or throw mydenyaccessexception exception            Base.            Checkauthorized (Authorizekey.listkey); string where=getpagercondition (); Pagerinfo Pagerinfo=Getpagerinfo (); List<DeviceCheckInfo> list = Basebll.findwithpager (where, Pagerinfo); //device code belongs to the Department brand category model equipment serial number check time processing personList<expandoobject> objlist =NewList<expandoobject>(); foreach(Devicecheckinfo Infoinchlist) {                Dynamicobj =NewExpandoObject (); DeviceInfo DeviceInfo= bllfactory<device>. Instance.findbycode (info.                Devicecode); if(DeviceInfo! =NULL) {obj. Dept=deviceinfo.dept; Obj. Brand=Deviceinfo.brand; Obj. Name=Deviceinfo.name; Obj. Model=Deviceinfo.model; Obj. Serialno=Deviceinfo.serialno; } obj.id=info.id; Obj. Devicecode=info.                Devicecode; Obj. Operatetime=info.                Operatetime; Obj. Operator=info.                Operator;            Objlist.add (obj); }            //JSON-formatted requirements {total:22,rows:{}}//structure to JSON format delivery            varresult =New{total = pagerinfo.recordcount, rows =objlist}; returntojsoncontentdate (Result); }

2) data display of the interface

The above defines the way data is obtained, that is, we need any data can be in the MVC controller, through the dynamic properties of adding to the collection object, thus simplifying the processing of our interface, we just need to display the information obtained in the interface can be very simple.

The HTML code for the interface view is shown below

            <TableID= "Grid"class= "Table table-striped table-bordered table-hover"cellpadding= "0"cellspacing= "0"Border= "0"class= "Display"width= "100%">                <theadID= "Grid_head">                    <TR>                        <!--device code belongs to the Department brand category model equipment serial number check time processing person -                        <thclass= "Table-checkbox"style= "width:40px"><inputclass= "Group-checkable"type= "checkbox"onclick= "SelectAll (this)"></th>                         <th>Device encoding</th>                         <th>Affiliated Departments</th>                         <th>Brand</th>                         <th>Category</th>                         <th>Model</th>                          <th>Device Serial Number</th>                        <th>Check Time</th>                        <th>Handling people</th>                        <thstyle= "width:90px">Operation</th>                    </TR>                </thead>                <tbodyID= "Grid_body"></tbody>            </Table>

We are bound to the interface, is the Ajax way to get the data, and then the binding display, JS code as shown below.

        functionsearchcondition (page, condition) {//get a collection of JSON objects and generate data display contenturl = "/devicecheck/findwithpager?page=" + page + "&rows=" +rows; $.getjson (URL+ "&" + condition,function(data) {$ ("#totalCount"). Text (data.total); $("#totalPageCount"). Text (Math.ceil (Data.total/rows)); $("#grid_body"). HTML (""); //<!--Equipment Coding Department brand category model equipment serial number check time processing person --$.each (Data.rows,function(I, item) {varTR = "<tr>"; TR+ = "<td><input class= ' checkboxes ' type=\" checkbox\ "name=\" checkbox\ "value=" + item.id + "></td>"; TR+ = "<td>" + item. Devicecode + "</td>"; TR+ = "<td>" + item. Dept + "</td>"; TR+ = "<td>" + item. Brand + "</td>"; TR+ = "<td>" + item. Name + "</td>"; TR+ = "<td>" + item. Model + "</td>"; TR+ = "<td>" + item. Serialno + "</td>"; TR+ = "<td>" + item. Operatetime + "</td>"; TR+ = "<td>" + item. Operator + "</td>"; TR+ = getactionhtml (item.id);//get view, edit, delete operation codeTR+ = "</tr>"; $("#grid_body"). Append (tr);                }); //setting paging properties and handling                varElement = $ (' #grid_paging '); if(Data.total > 0) {                    varOptions ={bootstrapmajorversion:3, Currentpage:page, Numberofpages:rows, Totalpa Ges:Math.ceil (Data.total/rows), onpagechanged:function(event, Oldpage, NewPage) {searchcondition (newPage, condition); //trigger Content Update when page changes}} element.bootstrappaginator (options); } Else{element.html ("");        }            }); }

The result is a graceful implementation of the interface we described earlier.

Using dynamic and ExpandoObject in the MVC controller to achieve data escaping output

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.