Ajax request asp.net MVC-isolated list data into a DTO instance

Source: Internet
Author: User

Our sample database script:


Use [db_users] Go/****** object:  table [dbo]. [student]    script date: 11/06/2015 00:01:52 ******/SET ANSI_ Nulls on go set quoted_identifier on down Set ansi_padding on go CREATE TABLE [dbo] . [Student] (    [s_id] [int] identity (1,1)  not null,     [s_ Name] [nvarchar] ( null),     [s_sex] [char] (2)  null,      [s_age] [int] null,     [c_id] [int] not null,   constraint [pk__studnet__2f3da3bc267aba7a] primary key clustered  (     [S_ID] ASC) with  (pad_index  = off, statistics_norecompute  =  off, ignore_dup_key = off, allow_row_locks  = on, allow_page_ Locks  = on)  on [PRIMARY])  on [primary] go to Set ansi_padding off go alter table [dbo]. [Student]  with check add foreign key ([c_id]) references [dbo]. [classes]  ([c_id]) go use [db_users] go/****** object:  table [dbo]. [classes]    script date: 11/06/2015 00:02:15 ******/SET ANSI_ Nulls on go set quoted_identifier on go create table [dbo]. [Classes] (    [c_id] [int] not null,     [c_name] [nvarchar] (m)  null, primary key clustered  (    [C_ID] ASC) WITH  (PAD_ index  = off, statistics_norecompute  = off, ignore_dup_key =  off, allow_row_locks  = on, allow_page_locks  = on)  ON  [primary])  on [primary] Go



Then create a new MVC project: Post a Frame chart:


Background code;
Controller's Code: using mvcajax01.models;
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc; namespace mvcajax01.controllers {    public class studentcontroller :  controller     {        ModelDB db 
= new modeldb ();         /// <summary>          ///  Generate Student List page         /// </summary>          /// <returns></returns>     
    public actionresult index ()         {
            return view ();        &nbSP;}         /// <summary>          ///  load data based on page number         /// </summary>          /// <param name= "id" >id parameters are actually uploaded to the corresponding pageindex in the page, then why use the ID , because this is configured in routing </param>         /// <returns></returns >         public actionresult list (int id)          {           
 int pageIndex = id;
            int pageSize = 3;             //Query Student Paging data              //pagination Steps: Orderby-->skip ((page 1) * page capacity)--->take (page capacity), and finally ToList ().             //list<student> list =  db. Students.orderby (s => s.s_id). Skip ((pageindex - 1)  * pagesize). Take (pageSize).
ToList ();             //to DTO entity              //This is a problem, db.
Students students or model below the efstudent entity, this time can be changed.             //list<mvcajax01.models.dto.student > list = db. Students.orderby (s => s.s_id). Skip ((pageindex - 1)  * pagesize). Take (pageSize).
ToList ();             //corrected (using the Select method to map to a DTO, In the inside to be new to each DTO)             // Converts the collection of F entities from the EF query into a DTO (data transfer object) Entity collection &nbsP;           //list<mvcajax01.models.dto.student>  list = db. Students.orderby (s => s.s_id). Skip ((pageindex - 1)  * pagesize). Take (pageSize). Select (S => new models.dto.student ()  {          &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//S_ID=S.S_ID,              //s_name=s.s_name,             //s_age=s.s_ Age,             //s_sex=s.s_sex,     &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//C_ID=S.C_ID,              //class=s.class                           //}). ToliSt ();     //tips: Here one attribute write is too tired, we can write a method entity class to the Dto method, add a class in model, write method.             //the Dto conversion method is written in the distribution class, this is not a select.
Write this directly.             //list<mvcajax01.models.dto.student > list = db. Students.orderby (s => s.s_id). Skip ((pageindex - 1)  * pagesize). Take (pageSize). Select (                          //   s=>s.todto ()    //There's a problem with this. The class attribute is not set just now.
It's time to make changes.             //).
ToList ();             //this time, you can modify the,   this way, but there are still questions to write, Is that the class attribute in the EF and the properties in the Dto are still different, so we're still making changes in the DTO, and we need to add a DTO class for the class setting          &nbSp;   //list<mvcajax01.models.dto.student> list = db. Students.orderby (s => s.s_id). Skip ((pageindex - 1)  * pagesize). Take (pageSize). Select (            //s => { var  sdto = s.todto ();  sdto.class = s.class; return sdto;                             //converts the collection of EF to a set of DTO entities and returns (for the use of the DTO class, note that the class name should not be the same as the EF entity class, or it will be an error.)
            //Then, here is also a mistake point: Take method must be tolist, or error.             List< Mvcajax01.models.dto.studentdto> list = db. Students.orderby (s => s.s_id). Skip ((pageindex - 1)  * pagesize). Take (pageSize). ToList (). Select (&nbsP;         s =>s.todto ()           ).
ToList ();             //get total number of rows              int rowcount = db.
Students.count ();             //Calculate Total Pages              int pagecount = convert.toint32 (Math.Ceiling (
rowcount * 1.0)) ( / pagesize));             //generate JSON-formatted data (if it's a hassle to build yourself, add a class yourself this time, Practice; We add a class under the Model folder              #region   Version             //without dto when using DTO              ////operations: Encapsulating data into pageddatamodel  paging data entities              ////package is very simple ah, is to assign value to the property Bai:             //// After the generic class is made, specify which class to             //PagedDataModel< Student> pagemodel = new pageddatamodel<student> ()              ////but anyway, in this pageddatamodel entity, it's just the data related to the pagination, and the data that you turn into JSON format, You want to turn him to Wow,             ////sent to the browser, the browser must want to know, in the end is success or not success AH , the state is what ah, so we have to prepare a class, this time is Jsonmodel             /// /We add a Josnmodel class             //{to the Model folder   After the            //    //data property is made generic,
This way you can directly assign the list value to data.            //    data =  list,             //     Pagecount = pagecount,             //     pagesize = pagesize,              //    rowcount = rowcount,              //    pageindex = pagesize    
         //};              #endregion               #region   version modifications after using the DTO              //operations: Encapsulating data into pageddatamodel             //encapsulation in a paging data entity it's easy to assign a value to a property:              //to the generic class, specify which class to              pageddatamodel<models.dto.studentdto> pagemodel =  new PagedDataModel<Models.DTO.StudentDTO> ()              //but anyway, in this pageddatamodel entity, it's just data related to the paging data, and you turn it into JSON format, you're going to turn him into Wow,              //sent to the browser, the browser must want to know, in the end is success or not success Ah, the state is what ah, so we have to prepare a class, This time it's Jsonmodel             //. Let's add a Josnmodel class to the Model folder             {  After the                //data property is made generic,
This way you can directly assign the list value to data.     &nBsp;           data = list,    
             pagecount = pagecount,                 PageSize  = pagesize,                  rowcount = rowcount,                  pageindex = pagesize          
   };                           //Summary of the above query student data, after the EF detected, turned to a set of DTO, (originally found in the EF student collection)               #endregion      &nbsp      //the paging data entity into the json  standard format entity              jsonmodel jsonmodel = new jsonmodel ()              {                 data = pagemodel,                  Message =  "Success"                  Status =  "OK"                  //BackUrl=   do not give,
There's nothing!
            };
             #region   These two lines of code, equivalent to the json  method         &nbsP;   // system.web.script.serialization.javascriptserializer jss = new
 system.web.script.serialization.javascriptserializer ();             //string str= jss.serialize (
list);              #endregion      &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//generates JSON-formatted data (via JSON method)       
     //This method, the interior is actually to help us call the JavaScriptSerializer serialization method, it is because of the call this method, so we are processing data here, the error: Circular reference. &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//EF generated entity classes, just easy to query, when really used, especially when serializing,
Or to turn into our own entity classes, this entity class, we call him a dto, we under the Model folder, create a new folder Dto, and then continue to add classes inside ...
            //Note:  Get the Dto collection, when serialized here, there will be no error.             //This JSON method, the default is to allow only post requests &NBSP;&NBSp;          return json (JsonModel,
Jsonrequestbehavior.allowget);
                   } &NBSP;&NBSP;&NBSP;&NBSP}}

Code for the




Index view:


@{    ViewBag.Title =  "Student List";} @section  headsection{     <script type= "Text/javascript" >         $ (function  ()  {            //to turn off jquery's browser cache              //The cache is turned off, each time a data is sent to the server to obtain the data    
         $.ajaxsetup ({ cache: false });             //Request first page data     
        loadpagelist (1);
        });         //asynchronously requests data based on page numbers         / /We read the data of the page, after the server read the data, directly generated HTML code sent over, displayed in the table good?
Or after the server gets the data, turn the data into JSON, send it to the browser, and then convert the browser to HTML code based on the JSON data.     &nbSp;   //josn Good, JSON has a smaller amount of transmission.         //with json  directly $.getjson (), or $.get ()                             function loadpagelist (pageIndex)         {             //and Getjson are about the same, missing the last parameter              //$.get ("Student/list"  + pageindex, null,  function  (jsondata)  {            /
/},  "JSON");
            //Note: Does the GET request use browser caching? Then we'd better clean out the browser cache.             //tricks Oh, you can use a global variable, turn the cache off              $.geTjson ("Student/list"  + pageIndex, null, function  (jsondata)  {   
             alert (JSONDATA.MSG);
            });         }     </script>               &nbsp} <table id= "Tblist" >      <tr>         <th>ID</th>          <th>Name</th>         <th>sex </th>         <th>Age</th>          <th>Class</th>         <th> Operate</th>     </tr>;/table> 




and then the code for two classes under each Dto folder:


using system;
using system.collections.generic;
using system.linq;
using system.web; namespace mvcajax01.models.dto {    /// <summary>     // The key point of the/ dto class is that we write our own class, not the proxy class, when we use it, we lift the code to find the query, modify the     ///       /// </summary>     public class classdto      {        //public class ()          //{        //    this.
Students = new hashset<student> ();         //}         public  int c_id { get; set; }         public  string c_name { get; set; }         //similarly this attribute also slightly to modify, remove virtual, in fact, the class inside, we do not know if there are students, to know, you can go to check, so this attribute removed, here on the comment          //public  ICollection<Student> Students { get;  set; }    &nbsp}}
using system;
using system.collections.generic;
using system.linq;
using system.web; The key point of the namespace mvcajax01.models.dto {    ///dto class is that we write the class ourselves, not the proxy class, when we use it, we lift the code to find the query, Modify the     /// <summary>     ///  entity slightly, just like the student entities in the EF
, just copy it over.
    /// </summary>     public class studentdto     {        public int s_id {  get; set; }         public string s_name  { get; set; }         public string s_ sex { get; set; }         public Nullable< int> s_age { get; set; }         public  int&nbspC_ID&NBSP;{&NBSP;GET;&NBSP;SET;&NBSP}         //only slightly modified for this property          public  ClassDTO Class { get; set;  }    &nbsp}}



Dto Transform method class:


using system;
using system.collections.generic;
using system.linq;
using system.web; namespace mvcajax01.models {    /// <summary>     ///   The name should be the same as EF, when it is merged into a method     /// </summary>     public  partial class student     {       #region   1.0 version    Claa property is not set first         //will ef student entity, Convert to DTO student entity         //1.0 version    do not set CLAA properties first          //public dto. Student todto ()         //{           // return new dto. Student ()         // {        &NBSP;//&NBSP;S_ID=THIS.S_ID,  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//&NBSP;C_ID=THIS.C_ID,          // s_sex=this.s_sex,         // //class=this. class,   here can't write directly, but here can not give, class is a foreign key, when needed, the time to query. Now back to the controller         // s_age=this.s_age,          // s_name=this.s_name             
      // };            #endregion           #region  2.0  version set class attribute         public dto. Studentdto todto ()         {             return new dto. Studentdto () &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp; {                s_id &NBSP;=&NBSP;THIS.S_ID,                &NBSP;&NBSP;C_ID&NBSP;=&NBSP;THIS.C_ID,                  s_sex = this.s_sex,                  //class=this. class,   here can't write directly, but here can not give, class is a foreign key, when needed, the time to query. Now back to the controller                 s_age  = this.s_age,                  s_name = this.s_name,                  class = this. Class.todto ()             };
         #endregion         } &NBSP;&NBSP;&NBSP;&NBSP}}
using system;
using system.collections.generic;
using system.linq;
using system.web; namespace mvcajax01.models {    /// <summary>     ///   The name should be the same as EF, when it is merged into a method     /// </summary>     public  partial class class     {         Public dto. Classdto todto ()         {             return new dto. Classdto ()             {     &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;C_ID=THIS.C_ID,                  c_name=this.c_name             &nbSP;};         }    &nbsp}}



Pagination Data entity classes:


using system;
using system.collections.generic;
using system.linq;
using system.web;
namespace mvcajax01.models {    //The attributes to be added are just calculated. After the     //is finished, serialize the class. Actions in controllers:      //operations: Encapsulating data into pageddatamodel  paging data entities     ///  <summary>     ///  Paging Data entity     /// </summary>      public class PagedDataModel<T>     {         /// <summary>         ///   Data         /// </summary>          public List<T> Data { get; set; }     //This data property, you should use the object type, of course, you can also use generics, specifically: Class writing generic class, return the data attribute to generics          /// <summary>         ///  page numbers (can be set or not set here)          /// </summary>         public  int pageindex { get; set; }         ///  <summary>         ///  page Capacity (can be set or not set here)          /// </summary>         public
 int pagesize { get; set; }                  /// <summary>          ///  Total Pages         /// </summary>          public int pagecount { get; set; }     &nbsP;    /// <summary>         ///  Total number of rows (totals)         /// </summary>          public int rowcount { get; set; }    &nbsp}}


Jsonmodel Entity classes:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Namespace Mvcajax01.models
{
///<summary>
///JSON data entity
///</summary>
Pub        Lic class Jsonmodel
{Public
object Data {get; set;}
public string Message {get; set;}
public string Status {get; set;}
public string Backurl {get; set;}
}
}


Finally, attach a few pictures:




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.