JS Frontend passes the JSON array to the server side and parses the implementation.

Source: Internet
Author: User

In a recent small project you need to pass the JSON array data to the server side to save, now share the solution.

Environment: EASYUI+MVC 4.0

As follows:

In the above section of the red circle, you need to save the data through an AJAX request after clicking Save.

Many projects have such a requirement, so it is important to understand the solution.

Analysis Process:

The red circle is divided into two pieces, one is a picture, including the field "Picture path" and "Picture description", you can infer the JSON data format {' picture path ': xxx, ' picture description ': xxx}.

A piece is a sub-item collection, containing the field "sub-item number" and "Memo", you can infer the JSON format {' Child item number ': XXX, ' remarks ': xxx}.

However, the two pieces of data are multiple, so think of JS "[]" (JS array ) for storage.

That is, you can write the following code:

   //picture entities are consistent with background properties    functionpart_pic (imgdescription, Imgurl) { This. Imgdescription =imgdescription;  This. Imgurl =Imgurl; return  This; }    //the child item entity is consistent with the background property    functionPart_children (Childmaterialnumber, Remark) { This. Childmaterialnumber =Childmaterialnumber;  This. Remark =Remark; return  This; }    //there is a function to fetch the data and populate it in the array   functionSave () {varPart_piclist = [];//defines an array of images for storing multiple picture information      varPart_childrenlist = [];//Define a sub-item array      //then get the data and populate it, here's an example      varpartpicobj=NewPart_pic (' This is a picture description ', ' This is a picture link '); Part_piclist.push (Partpicobj); //Fill}

Well, here's a key point, how to pass these two JS arrays to the server and parse.

The JSON serialization and deserialization knowledge is used here.

The general Ajax requests are as follows:

    $.ajax ({               "/part/get_details",            "POST"            , "JSON",            "ID": row["ID"}            ,function  (res) {               //  what             to do},             function (Error) {                alert (json.stringify (Error));            }        });

For "data", directly passing the JS array, the server is receiving such a thing "[Object,object]", it is visible that the server does not know it at all.

Fortunately, JS has a serialization function that serializes the object into a "JSON string."

Json.stringify (worklist)  //Microsoft Official explanation: https://msdn.microsoft.com/library/cc836459 (v=vs.94). aspx
Parametersvalue

    required.  

return value

  A string that contains JSON text.

This means that the "JS array " is serialized through the function and a new " string " is created. The " string " is recognizable to the server side, regardless of the language.

Then the AJAX request can be written like this:

  $.ajax ({URL:  "/part/get_details"  Ty PE:  "POST" " JSON ", data: 
{ "id": row["id" " part_childrenlist ":json.stringify (Part_childrenlist)//serialization}, Success: function (RES) { // What do you do? }, error: function (Error) { Alert (json.stringify (error));    // This place also uses

Well, the next problem to solve is how to parse the server and use the object deserialization .

What I'm using here is Newtonsoft.json, which is referenced by default in the MVC4.0 project.

Newtonsoft.Json.JsonConvert is a free Json conversion tool from Microsoft.

Newtonsoft.json is the. NET open source Json format sequence number and the deserialized class library.

Usage:
New list< entities >= newtonsoft.json.jsonconvert.deserializeobject<list< entities >> ("  JSON string "from the foreground );

That's the word. The deserialization of the JSON string is completed . PS: It's really simple.

At this point, there is a complete solution to the idea, followed by the work of the Code.

Part of the code:

//picture entities are consistent with background properties    functionpart_pic (imgdescription, Imgurl) { This. Imgdescription =imgdescription;  This. Imgurl =Imgurl; return  This; }    //the child item entity is consistent with the background property    functionPart_children (Childmaterialnumber, Remark) { This. Childmaterialnumber =Childmaterialnumber;  This. Remark =Remark; return  This; }         //Save    functionsaveentity () {//define a collection of pictures        varPart_piclist = []; $.each ($ ("#yulan_div"). Find ("div"),function () {            varDesobj = $ ( This). Find ("Input[name= ' imgdescription ']"); varUrlobj = $ ( This). Find ("div"). Find ("Img[name= ' Imgurl ']"); if(Desobj.length > 0 && urlobj.length > 0) {                varPicobj =NewPart_pic (Desobj.val (), urlobj.attr ("src")); Part_piclist.push (Picobj); //populating an array            }        }); //define a child item collection        varPart_childrenlist = []; $.each ($ ("#childrentable tbody tr"),function () {            varChildrenobj =NewPart_children (); varTdobj = $ ( This). Find ("TD"); $.each (Tdobj,function(index) {//whether there is a text box                varHasText = Tdobj.find ("input[type= ' text ']"). length; if(HasText <= 0)                {                    //Child Item Number                    if(Index = = 1) {childrenobj. Childmaterialnumber= $( This). html (); }                    Else if(index = = 2)//Notes{childrenobj. Remark= $( This). html ();                       }                }            }); if(Childrenobj. Childmaterialnumber! =undefined) {Part_childrenlist.push (childrenobj);//populating an array            }        }); $(' #fmDetail '). Form (' Submit ', {URL:"/part/save", OnSubmit:function(param) {//triggered upon commit                //Easyui Adding parameters when submittingParam. Part_piclist = Json.stringify (part_piclist);//Key, JSON serialization of an array, otherwise it cannot be delivered to the server .Param. Part_childrenlist =json.stringify (part_childrenlist); varFlag = $ ( This). Form (' Validate ');//whether to pass validation                if(flag) {$ (' #grid '). DataGrid ("Loading");//If you verify that the DataGrid displays the load status                }                returnFlag; }, Success:function(res) {if(res = = "OK"{$.messager.show ({title:' Operation Tips ', msg:' &nbsp;&nbsp; saved successfully ', timeout:2000, ShowType:' Slide '                    }); $(' #DivAdd '). Dialog (' Close ');//Close the popup box$ (' #fmDetail '). Form (' clear ');//clears the form data. $ (' #btnSearch '). Click ();//Reload Data                }                Else{$.messager.show ({title:' Error hints ', msg:' &nbsp;&nbsp; save failed! Contact your administrator or try to re-operate. ‘, timeout:0, Width:320, ShowType:' Slide '                    }); }            }        })    }
front-end JS (includes Easyui usage)
 Public voidSetchildren (Partview entity) {entity. Part_piclist= Newtonsoft.json.jsonconvert.deserializeobject<list<part_pic>> (request["part_piclist"]); Entity. Part_childrenlist= Newtonsoft.json.jsonconvert.deserializeobject<list<part_children>> (Request["part_childrenlist"]); BOOLResultchild = Part_ChildrenBLL.Instance.Where ("[email protected]"). Parms (entity.id). Update ("isdel=1"); if(resultchild) {foreach(varIteminchentity. Part_childrenlist) {Item. PartID=entity.id; PART_CHILDRENBLL.INSTANCE.ADD (item,New string[] {"PartID","Childmaterialnumber","Remark" }); }            }            BOOLResultpic = Part_PicBLL.Instance.Where ("[email protected]"). Parms (entity.id). Update ("isdel=1"); if(resultpic) {foreach(varIteminchentity. Part_piclist) {Item. PartID=entity.id; PART_PICBLL.INSTANCE.ADD (item,New string[] {"PartID","Imgurl","imgdescription" }); }            }        }
C # server-side code

Poor writing, please advise.

Diligence is a kind of life attitude, how you treat life, life is how to treat you.

JS Frontend passes the JSON array to the server side and parses the implementation.

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.