Asp.net+easyui Implementing a basic crud

Source: Internet
Author: User
Tags tojson

today, Thursday, should give themselves a vacation, a good rest, but helpless to it is really obsessed with, willingly want to add overtime to achieve the goal function, Kung fu not negative, after 6 hours of battle, I finally succeeded. Here and We share the results, I hope you give a praise.

My goal effect: When the page is loaded, table tables display the information of the students in the Background data table; Click the Add button, the box appears, you can add student information, select a student record, click the Edit button, the pop-up box, you can modify the student information; Select a student record, click the Delete button, To delete the student's information. As shown below:

Target effect has, talk about the realization of ideas.

1. Need to introduce the Easyui class library and related js:

2. Draw a table with the data displayed

//used to deliver the actions the user needs to perform <input id= "test" name= "test" type= "hidden" > <!--Table Display area--<table id= "tt" "title=" Manage Student Information "class=" Easyu I-datagrid "style=" Width:auto; height:400px; "idfield=" Itemid "pagination=" true "iconcls=" Icon-save "remotesort=" false "data-options=" Rownumbers: True, url: ' Jsondata.ashx/processrequest ', pagesize:5,pagelist:[5,10,15,20], method: ' Get ', toolbar: ' #tb ', ' fit Columns= "true" striped= "true" singleselect= "true" > <thead> <tr> <th da ta-options= "field: ' Serial ', width:0" hidden= "hidden" > Serial number </th> <th data-options= "field: ' ID ', width : ", sortable:" True "> Study number </th> <th data-options=" field: ' Name ', width:100 ", sortable:" true "> Name &L t;/th> </tr> </thead> </table> 
3. Draw Add, modify, delete three buttons

<!--Add, modify, delete buttons    --<div id= "TB" >        <a href= "javascript:void (0)" class= "Easyui-linkbutton" iconcls= "Icon-add" plain= "true" onclick= "NewUser ()" > Add student </a>         <a href= "javascript:void (0)" class= " Easyui-linkbutton "  iconcls=" Icon-edit "plain=" true "onclick=" Edituser () "> Modify student </a>         <a href=" Javascript:void (0) "class=" Easyui-linkbutton "iconcls=" Icon-remove "plain=" true "onclick=" Destroyuser () "> Delete student </a>    </div>
4. Draw a bullet box that appears when you click Add or modify a button

<!--bullet Frame--    <div id= "dlg" class= "Easyui-dialog" style= "width:400px; height:280px; padding:10px 20px"        Closed= "true" buttons= "#dlg-buttons" >        <div class= "Ftitle" >            User information</div>        < Form id= "FM" method= "POST" novalidate>        <div class= "Fitem" >            <label> Study No.:</label>            <input id= "id" class= "easyui-validatebox" required= "true" >        </div>        <div class= "Fitem" >            <label> name:</label>            <input id= "name" class= "Easyui-validatebox" required= "true" >        </div>        </form>    </div>
To the Display section of this page, the following need to use Ajax to establish the interaction between the Web page and the general handler

var url = "Jsondata.ashx/processrequest";//Open Add Student box function NewUser () {$ (' #dlg '). Dialog (' Open '). dialog (' Settitle ', ' Add students '); Set the header $ (' #fm '). Form (' clear '); Clears the form data document.getElementById ("test"). Value = "Add";    Setting represents a different method for background tuning data provided interface}//Open Modify student box function Edituser () {$ (' #fm '). Form (' clear ');    var row = $ (' #tt '). DataGrid (' getselected ');        if (row) {$ (' #dlg '). Dialog (' Open '). dialog (' Settitle ', ' modify student ');        Bound data List $ (' #id '). Val (row.id);        $ (' #name '). Val (Row.name); document.getElementById ("Test"). Value = "Modify";    Sets the interface $ (' #fm ') that represents the different method data for a background tune. Form (' Load ', row);    }}//Save information Function Saveuser () {//Gets the value entered in the page var serial;    var id = document.getElementById ("id"). value;    var name = document.getElementById ("name"). Value;    var test = document.getElementById ("Test"). Value;    var row = $ (' #tt '). DataGrid (' getselected ');    if (test = = "Modify") {serial = row.serial;    } else {serial = = ""; } $ (' #fm '). foRM (' Submit ', {//set address and pass parameters to background URL: "jsondata.ashx?id=" + ID + "&name=" + name + "&test=" + Test +        "&serial=" + Serial, Onsubmit:function () {return $ (this). Form (' Validate '); },//Determine if the result is correct success:function (result) {if (Result.indexof ("T") = = 0) {alert (' Congratulations, the information is saved successfully!      ') $ (' #dlg '). Dialog (' Close ');            Close the window $ (' #tt '). DataGrid (' reload '); } else {alert (' Save failed, please check!            ')} var result = eval (' (' + result + ') ');      if (result.success) {$ (' #dlg '). Dialog (' Close ');                Close the dialog $ (' #tt '). DataGrid (' reload '); $.message.alert (' Hint ', ' save success!                ', ' info ');                  Reload the user data} else {//$.messager.show ({//title: ' Error ',      Msg:result.msg//});        }        }    });}  Delete student function Destroyuser () {document.getElementById ("test"). Value = "Delete";//Set represents a different method for background tuning data supply interface var test =    document.getElementById ("Test"). Value;    var row = $ (' #tt '). DataGrid (' getselected '); if (row) {$.messager.confirm (' hint ', ' Are you sure you want to delete this message? ', function (r) {if (R) {$ (' #fm '). Form (' Submit ', {URL: "Jsondata.ashx?seri                    Al= "+ row.serial +" &test= "+ Test, Onsubmit:function () {},                            Determine if the result is correct success:function (result) {if (Result.indexof ("T") = = 0) {                            $ (' #dlg '). Dialog (' Close '); Alert (' Congratulations, the message was deleted successfully!                        ') $ (' #tt '). DataGrid (' reload '); } else {alert (' Add failed, please re-operate! ')} var result = eval (' (' + result + '))');            }                });    }        }); }}
through the JS code, we can find that Ajax obtains the user's data, submits it to the general handler jsondata.ashx for processing, and uses the callback function to get the execution result of the general handler, the JSONDATA.ASHX code is as follows:

  Studentdal studentdal = new Studentdal ();              public void ProcessRequest (HttpContext context)//context contains values passed back and forth between foreground and background {//to determine which of the foreground requests are additions and deletions string command = Context.                  request.querystring["Test"];//the foreground value if (Command = = "Add") {//Call to Add method            ADD (context);            } else if (Command = = "Delete") {//Call Delete method Delete (context);            } else if (Command = = "Modify") {//Call Modify method Modify (context);            } else {//Invoke Query method (context);  }} #region Add record///<summary>///Add record///</summary>//<param Name= "context" ></param> public void Add (HttpContext context) {Studententity student =            New Studententity (); Student.id = context. Server.urldecode (context. request.querystring["id"]); Student.name = context. Server.urldecode (context.            request.querystring["name"]); try {if (Studentdal.add (student)) {context.                Response.Write ("T"); } else {context.                Response.Write ("F");        }} catch (Exception ex) {}} #endregion #region modify the record         <summary>///Modify record///</summary>//<param name= "context" ></param>            public void Modify (HttpContext context) {studententity student = new Studententity (); Student.serial = context. Server.urldecode (context.            request.querystring["Serial"]); Student.id = context. Server.urldecode (context.            request.querystring["id"]); Student.name = context. Server.urldecode (context.            request.querystring["name"]);  try {              if (Studentdal.update (student)) {context.                Response.Write ("T"); } else {context.                Response.Write ("F");        }} catch (Exception ex) {}} #endregion #region Delete record         <summary>//Delete records///</summary>//<param name= "context" ></param>            public void Delete (HttpContext context) {studententity student = new Studententity (); Student.serial = context. Server.urldecode (context.            request.querystring["Serial"]); try {if (Studentdal.delete (student)) {context.                Response.Write ("T"); } else {context.                Response.Write ("F");      }} catch (Exception ex) {      }} #endregion #region query Records//<summary>///</summary            >//<param name= "context" ></param> public void Query (HttpContext context) { Context.            Response.ContentType = "Text/plain";            Call the GetList method of paging DataSet ds = Studentdal.query (); String Strjson = Tojson.dataset2json (ds,-1);//dataset data into JSON data context. Response.Write (Strjson);//Return to the foreground page context.        Response.End (); } #endregion
when data in a data table is bound to a table in a page, the result returned in the background is a dataset or DataTable type, so a method is required to convert the dataset or DataTable to a JSON type. The powerful Tojson class completes the above tasks:

public class ToJson {#region DataSet converted to JSON format///<summary>///DataSet converted to JSON format/          </summary>//<param name= "DS" >DataSet</param>//<returns></returns> public static string Dataset2json (DataSet ds, int total =-1) {StringBuilder json = new string            Builder (); foreach (DataTable dt in DS. Tables) {//{"total": 5, "Rows": [JSON.                Append ("{\" total\ ":"); if (total = =-1) {JSON. Append (dt.                Rows.Count); } else {json.                Append (total); } JSON.                Append (", \" rows\ ": ["); Json.                Append (Datatable2json (DT)); Json.            Append ("]}"); } return JSON.        ToString (); } #endregion convert #region DataTable to JSON format///<summary>//DataTable to JSOn format///</summary>//<param name= "DT" ></param>//<returns></ret urns> public static string Datatable2json (DataTable dt) {StringBuilder Jsonbuilder = new St            Ringbuilder (); for (int i = 0; i < dt. Rows.Count;                i++) {jsonbuilder.append ("{"); for (int j = 0; j < dt. Columns.count;                    J + +) {jsonbuilder.append ("\" "); Jsonbuilder.append (dt. COLUMNS[J].                    ColumnName);                    Jsonbuilder.append ("\": \ ""); Jsonbuilder.append (dt. ROWS[I][J].                    ToString ());                Jsonbuilder.append ("\", "); } if (dt.                Columns.count > 0) {jsonbuilder.remove (jsonbuilder.length-1, 1);            } jsonbuilder.append ("},"); } if (dt. Rows.Count > 0) {jsonbuiLder.            Remove (jsonbuilder.length-1, 1);        } return jsonbuilder.tostring (); } #endregion DataTable into JSON format}
at this point, the core code has been implemented, and the rest is a student entity--studententity, a visit to the T_student table Studentdal class, they and we usually access the database, the same way, do not repeat this.
This allows us to easily perform crud operations on the data table t_studnet. Although the basic functionality has been implemented, but Easyui's many extensions need to continue to understand, such as in the data display, you can set how many data per page, the way the data sorted, combined query and other functions.

This demo greatly increased my confidence in learning Easyui, I thought it would take a week to complete the function, did not expect two days to fix, small to be a bit. and Easyui similar to the ExtJS, they can draw a very good page diagram, but Easyui is the framework of jquery, ExtJS is the framework of Ajax.

If you want to practice practiced hand, can I do a good demo download down, to see what I do not know the code, welcome to the big God shot brick, Source: http://pan.baidu.com/s/1o6Cz4Qe.

Well, today first, Renhan called to let us go home to the dumplings, about Easyui study, we will talk another day.         

Related Article

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.