JSON data of ASP. NET frontend and backend interaction, asp. netjson

Source: Internet
Author: User

JSON data of ASP. NET frontend and backend interaction, asp. netjson

Recently, due to the need for Ajax to collect multiple data from a single form, therefore, the front-end JQuery is used to save the Object and convert it into a JSON data source and pass it to the backend for processing. I believe many people often receive the JSON data format provided by the backend, get the front-end display format. Of course, this is my personal experience introduction. Do not spray it. The purpose of this article is to forget to be able to help the meeting in the future. Maybe it can really help some cainiao like me who are not deeply involved in the world. O (partition _ partition) O

The following are some key code

The first is the HTML code:

<Fieldset> <legend> Basic Information </legend> <div class = "add_main" id = "wrapper_add"> <div id = "errorInfo" class = "error container"> </div> <table width = "100%" border = "0" cellpadding = "0" cellspacing = "0" class = "addForm"> <tr> <th> target object: </th> <td> <asp: textBox ID = "obj_tbx" ClientIDMode = "Static" CssClass = "input" runat = "server" Width = "280px"> </asp: textBox> </td> <th width = "18%"> Workgroup: </th> <td width = "32%"> <asp: DropDownL Ist ID = "Group_ddl" ClientIDMode = "Static" runat = "server" Width = "120px"> </asp: dropDownList> </td> </tr> <th width = "18%"> project category: </th> <td width = "32%"> <asp: dropDownList ID = "ProjectType_ddl" ClientIDMode = "Static" runat = "server" Width = "200px"> </asp: dropDownList> </td> <th width = "18%"> level points: </th> <td width = "32%"> <asp: dropDownList ID = "score_ddl" ClientIDMode = "Static" runat = "server" Width = "120px"> </asp: DropDownList> </td> </tr> <th> target address: </th> <td colspan = "3"> <uc1: city ID = "City1" runat = "server"/> <input id = "adress_tbx" type = "text" class = "input"> <script type = "text/javascript" charset = "UTF-8"> var TaskAddressArray = new Array (); // task address set var TaskArray = new Array (); // task set // Array Remove-By James (MIT Licensed) Array. prototype. remove = function (from, to) {var rest = this. slice ((To | from) + 1 | this. length); this. length = from <0? This. length + from: from; return this. push. apply (this, rest) ;}; // obtain the task Object information function gettaskmodel (Addresslist) {var taskmodel = new Object (); taskmodel. goal = $ ("# obj_tbx "). val (); // target object taskmodel. group = $ ("# Group_ddl "). val (); // taskmodel of the workgroup value. groupName = $ ("# Group_ddl "). find ("option: selected "). text (); // taskmodel. projectType = $ ("# ProjectType_ddl "). val (); // The taskmodel of the project category. projectTypeName = $ ("# ProjectType_ddl "). find ("option: selected "). text (); // project category name taskmodel. score = $ ("# score_ddl "). val (); // level point value taskmodel. scoreName = $ ("# score_ddl "). find ("option: selected "). text (); // level point name taskmodel. carryDate = $ ("# request_tbx "). val (); // The completion time taskmodel. special = $ ("# special_tbx "). val (); // special requirements taskmodel. address = Addresslist; // taskmodel of the task Address set. uploadFile = eval ($ ("# hdJSON "). val (); // get the Upload File return Taskmodel;} // get address Object information function gettaskaddressmodel () {var taskaddress = new Object (); // investigate the address taskaddress. province = $ ("# ddl_province "). val (); // The province code taskaddress. provinceName = $ ("# ddl_province "). find ("option: selected "). text (); // The province name taskaddress. city = $ ("# ddl_city "). val (); // city code taskaddress. cityName = $ ("# ddl_city "). find ("option: selected "). text (); // city name taskaddress. counties = $ ("# ddl_counties "). Val (); // region code taskaddress. countiesName = $ ("# ddl_counties "). find ("option: selected "). text (); // region name taskaddress. detail = $ ("# adress_tbx "). val (); // return taskaddress;} // clear the form function ClearForm () {$ ("# obj_tbx "). val (""); $ (". addForm select "). find ("option [value =''] "). attr ("selected", true); $ ("# request_tbx "). val (""); $ ("# special_tbx "). val (""); $ ("# adress_tbx "). val (""); $ ("# hdJSON "). val (""); $ ("# t B _fileview "). attr ("style", "display: none"); $ ("# tb_fileview "). find ("tbody" ).html (""); TaskAddressArray = []; // clear the address array ShowAddress () ;}// assign a value to the form function SetForm (index) {$ ("# obj_tbx "). val (TaskArray [index]. goal); $ ("# Group_ddl "). find ("option [value = '" + TaskArray [index]. group + "']"). attr ("selected", true); $ ("# ProjectType_ddl "). find ("option [value = '" + TaskArray [index]. projectType + "']"). attr ("selecte D ", true); $ (" # score_ddl "). find ("option [value = '" + TaskArray [index]. score + "']"). attr ("selected", true); $ ("# request_tbx "). val (TaskArray [index]. carryDate); $ ("# special_tbx "). val (TaskArray [index]. special); $ ("# hdJSON "). val (JSON. stringify (TaskArray [index]. uploadFile); TaskAddressArray = TaskArray [index]. address; ShowAddress (); ShowUpLoadFile (index); $ ("# btn_release, # btn_add "). attr ("style", "displa Y: none "); $ (" # btn_update "). removeAttr ("style "). attr ("onclick", "UpdateForm (" + index + ")");} // update the list function UpdateForm (index) {var TaskModel = gettaskmodel (TaskAddressArray ); clearForm (); TaskArray. splice (index, 1, TaskModel); ShowTaskView (); $ ("# btn_release, # btn_add "). removeAttr ("style"); $ ("# btn_update "). removeAttr ("onclick "). attr ("style", "display: none");} // Add address event function Address_Click () {Var TaskAddressModel = gettaskaddressmodel (); if (TaskAddressModel. province = "" | TaskAddressModel. city = "" | TaskAddressModel. counties = "" | TaskAddressModel. detail = "") {alert ("the address you entered is incomplete. Please complete it! "); Return;} TaskAddressArray. push (TaskAddressModel); ShowAddress () ;}// display address function ShowAddress () {$ ("# result" ).html (""); for (var I = 0; I <TaskAddressArray. length; I ++) {$ ("# result "). append ("<p>" + TaskAddressArray [I]. provinceName + TaskAddressArray [I]. cityName + TaskAddressArray [I]. countiesName + TaskAddressArray [I]. detail + "<a href = \" javascript: void (0); \ "onclick = \" RemoverAddress_Clic K ("+ I +") \ "> Delete </a> </p>") ;}} function ShowUpLoadFile (index) {var FileArray = eval ($ ("# hdJSON "). val (); if (FileArray. length> 0) {$ ("# tb_fileview "). removeAttr ("style"); $ ("# tb_fileview "). find ("tbody" 2.16.html (""); for (var I = 0; I <FileArray. length; I ++) {var trStr = "<tr>" + "<td>" + FileArray [I]. fileName + "</td>" + "<td>" + FileArray [I]. fileSize + "</td>" + "<td>" + "<a href = \" javascript: Void (0) \ "onclick = \" RemoveFileView_Click ("+ I +") \ "> Delete </a> </td>" + "</tr> "; $ ("# tb_fileview "). find ("tbody "). append (trStr) ;}}// remove the Upload File function RemoveFileView_Click (index) {var FileArray = eval ($ ("# hdJSON "). val (); FileArray. remove (index); $ ("# hdJSON "). val (JSON. stringify (FileArray); ShowUpLoadFile () ;}// remove the address Array function RemoverAddress_Click (id) {TaskAddressArray. remove (id); ShowAddress ();} // Remove the task Array function RemoveTaskView_Click (id) {TaskArray. remove (id); ShowTaskView ();} // Add the subtask function AddSubtasks_Click () {if (TaskAddressArray. length = 0) {alert ("You have not added the task address. Please add the task address correctly! "); Return;} var TaskModel = gettaskmodel (TaskAddressArray); ClearForm (); TaskArray. push (TaskModel); ShowTaskView () ;}// task list function ShowTaskView () {$ ("# tb_taskview "). find ("tbody" pai.html (""); if (TaskArray. length = 0) {alert ("no valid task data found! "); Return;} var ico =" "; for (var I = 0; I <TaskArray. length; I ++) {if (I = 0) {ico = "<span style = \" color: red; font-weight: bold; \ "> (master) </span> ";}else {ico =" <span style = \ "color: green; font-weight: bold; \"> (times) </span> ";} var trStr = "<tr>" + "<td>" + ico + "</td>" + "<td>" + TaskArray [I]. groupName + "</td>" + "<td>" + TaskArray [I]. projectTypeName + "</td>" + "<td>" + TaskArray [I]. scoreName + "</Td>" + "<td>" + TaskArray [I]. goal + "</td>" + "<td>" + TaskArray [I]. address [0]. provinceName + "</td>" + "<td>" + TaskArray [I]. address [0]. cityName + "</td>" + "<td>" + TaskArray [I]. address [0]. countiesName + "</td>" + "<td>" + TaskArray [I]. address [0]. detail + "</td>" + "<td>" + TaskArray [I]. carryDate + "</td>" + "<td>" + TaskArray [I]. special + "</td>" + "<td>" + "<a href = \" javascript: void (0 )\" Onclick = \ "SetForm (" + I + ") \"> edit </a> "+" <a href = \ "javascript: void (0) \ "onclick = \" RemoveTaskView_Click ("+ I +") \ "> Delete </a> </td>" + "</tr> "; $ ("# tb_taskview "). find ("tbody "). append (trStr) ;}}// submit task information function SubmitTask_Click () {if (TaskArray. length = 0) {alert ("no task information can be submitted. Please confirm that the task has been added! "); Return;} if (confirm (" are you sure you want to submit this task? ") {$. Ajax ({type:" POST ", dataType:" JSON ", url:"/AjaxHandler/TaskHandler. ashx? Action = save ", data: {TaskModel: JSON. stringify (TaskArray)}, success: function (data) {if (data. code = 0) {if (confirm (data. msg) {location. href = "TaskTracking. aspx ";} else {location. href = location. href ;}} else {alert (data. msg) ;}}, error: function () {alert ("task information submission failed. Please try again later or contact the administrator! ") ;}}}}</Script>

Processing interface code:

Using Newtonsoft. json; using System. collections. generic; using System. linq; using System. web; using IMPlatform. web. app_Code; using IMPlatform. domainEntities; using IMPlatform. service. business; using IMPlatform. service; using System. web. sessionState; namespace IMPlatform. web. ajaxHandler {// <summary> // TaskHandler abstract description /// </summary> public class TaskHandler: IHttpHandler, IRequiresSessionS Tate {IMPlatform. web. app_Code.BackJson <Task []> _ json = new App_Code.BackJson <Task []> (); TaskService tService = new TaskService (); TaskTypeService ptService = new TaskTypeService (); taskLogService tlogService = new TaskLogService (); public void ProcessRequest (HttpContext context) {string action = context. request ["action"] = null? "": Context. request ["action"]. toString (); switch (action) {case "save": SaveTask (context); break; default: _ json. code =-10; _ json. msg = "parameter error! "; Context. response. write (JsonConvert. serializeObject (_ json); break ;}} public bool IsReusable {get {return false ;}} /// <summary> // Save the task information /// </summary> /// <param name = "context"> </param> private void SaveTask (HttpContext context) {try {string taskStr = context. request ["TaskModel"] = null? "": Context. request ["TaskModel"]. toString (); PermissionLogic logic = new PermissionLogic (System. web. httpContext. current); string userid = logic. currentUserInfomation. userID; List <Task> TaskModelList = JsonHelper <Task>. jsonToList (taskStr); string MainNum = ""; // foreach (Task item in TaskModelList) {task TaskEntity = new task (); TaskEntity. address = item. address [0]. detail; TaskEntity. areaId = Item. address [0]. counties; TaskEntity. cityId = item. address [0]. city; TaskEntity. provinceId = item. address [0]. province; TaskEntity. createDate = DateTime. now; TaskEntity. creator = userid; TaskEntity. grade = Convert. toInt32 (item. score); System. collections. generic. list <task> list = tService. getTaskList (); bool flag = true; string num = ""; while (flag) {num = String. format ("{0: D6}", new Random (). nex T (999999); if (list. where (x => x. taskNo = num ). count () = 0) {flag = false;} TaskEntity. taskNo = num; TaskEntity. parentTaskNo = MainNum; if (MainNum = "") {MainNum = num;} TaskEntity. projectTypeID = item. projectType; TaskEntity. requireFinishDate = Convert. toDateTime (item. carryDate); TaskEntity. specialRequest = item. special; TaskEntity. targetObject = item. goal; TaskEntity. taskId = Guid. new Guid (). toString (); TaskEntity. taskStatus = 0; TaskEntity. group = item. group; # region Organization Address List <taskaddress> addresslist = new List <taskaddress> (); foreach (TaskAddress Address in item. address) {taskaddress tk_address = new taskaddress (); tk_address.ProvinceId = Address. province; tk_address.CityId = Address. city; tk_address.AreaId = Address. counties; tk_address.Address = Address. detail; addressl Ist. Add (tk_address) ;}# endregion # region organization uploads file information if (item. UploadFile! = Null) {List <taskfile> tflist = new List <taskfile> (); foreach (var File in item. uploadFile) {taskfile tf = new taskfile (); tf. fileName = File. fileName; tf. filePath = File. filePath; tf. saveFileName = File. saveName; tf. taskId = TaskEntity. taskId; u_user user = new PermissionLogic (HttpContext. current ). currentUser; tf. uploadUser = user! = Null? User. userID: Guid. empty. toString (); tf. uploadDate = DateTime. now; tf. fileStatus = 1; tflist. add (tf);} tService. addTaskFile (tflist) ;}# endregion tService. addTask (TaskEntity, addresslist);} _ json. code = 0; _ json. msg = "task published successfully! Go to task management to view? "; Context. response. write (JsonConvert. serializeObject (_ json);} catch (Exception ex) {_ json. code =-1; _ json. msg = "system exception. Please try again later! Exception Message: "+ ex. Message; context. Response. Write (JsonConvert. SerializeObject (_ json ));}}}}

Note that during deserialization of processing functions, you must create a Model that is the same as the JSON data organized by your front-end as the carrier of deserialization, after successful deserialization, the operation is simpler. You can simply perform operations on the data according to your business logic.

Haha, I have made an axe to my class at the place where the experts gathered. Please point out and share the mistakes in the article with the readers. Let's make progress together!


How can I log on to the front-end jQuery easyui and the backend aspnet (c #) and transmit data in the json data format to help you?

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "www.w3.org/..al.dtd">
<Html xmlns = "www.w3.org/5o/xhtml">
<Head>
<Title> Get </title>
<Style type = "text/css">
. Text
{
Border: 1px solid red;
Background-repeat: repeat-x;
Background-position: bottom;
}
</Style>

<Script src = "../Scripts/jquery-1.4.1.js" type = "text/javascript"> </script>

<Script type = "text/javascript">
$ (Function (){
$ Error = $ ("<font color = 'red'> the user name cannot be blank! </Font> ");
$ ("# TxtUserName"). keyup (function (){
If ($ ("# txtUserName"). val () = ""){
$ (This). addClass ("Text ");
} Else {
$ (This). removeClass ("Text ");
}
});
$ ("# TxtUserName"). blur (function (){
If ($ ("# txtUserName"). val () = ""){
$ (This). addClass ("Text ");
} Else ...... remaining full text>

Aspnet + JavaScript + JSON

Are there any problems with http requests and responses for front-end and back-end data transmission?
For the display of the Gridview, The Gridview is a background control and cannot be used directly at the foreground. It can only be used to present row and column data in tables.
You can use ajax to obtain and load ashx to the front-end for processing and rendering. As for whether you want to use ajax, I am afraid there are not so many options, and you are not willing to use third-party components to write them on your own.

If you are not familiar with ajax or http, it is difficult to solve this problem. The core of front-end and back-end interaction of web pages is http requests and responses. This is the key, every time you enter the URL and open the webpage, isn't it the process of submitting an http request, obtaining the webpage source code, and loading it by the browser?

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.