Two methods of JS submitting object array to C # server

Source: Internet
Author: User

method One: Use Ajax

1 Client JS code:

Get Object array function getqas ()  {    var stuAnswerList = [];      var stuAnswer = {  ' Answerid ': 1,  ' answertype ': 1,  ' Answercontent ':  ' one ',  ' answersingle ': 1,  ' answermultiple ':  ' 1,2 ' ",  ':
 true };     var stuAnswer1 = {  ' Answerid ': 1,  ' answertype ':  1,   ' answercontent ':  ' two ',  ' answersingle ': 1,  ' answermultiple ':  ', 1,2 ',  '
Answertof ': true };
    stuanswerlist.push (Stuanswer);
        stuanswerlist.push (Stuanswer);
return stuanswerlist; //ajax Submit Data Function submitstuanswersajax (Stuanswerarr)  {    $.ajax ({         url:  ". /.. /paper/submitstuanswers ",         type: " post ",          data: { stuanswerarr: stuanswerarr },          async: false,         cache:  false,         error: function  (xmlhttprequest,  Textstatus, errorthrown)  {            if   (xmlhttprequest.status == 1001)  {         
       eval (Xmlhttprequest.responsetext);             } else {   
             alert ("GetPaper error");             }         &NBSP},         success: function  (data)  {         
   alert (data);
        }     }); //Button click Method function submitstuanswersbtn ()  {    var stuAnswerArr = 
Getqas ();
    submitstuanswersajax (Stuanswerarr); }



2) service-side C # code:

Stuanswerentity public class stuanswerentity         {             public int answerID {  set; get; }             public int  answertype { set; get; }              public int answersingle { set; get; }              public string answerMultiple { set; get;  }             public bool answertof  { set; get; }              public string answercontent { set; get; }          }//stuanswerarr  Note that the front and back variable names must be the same public actionresult submitstuanswers (list<stuanswerentity>  stuanswerarr) {    bool re = false;     List<
Stuanswerentity> stuanswerentitylist = new list<stuanswerentity> ();
    stuAnswerEntityList = stuAnswerArr;     //at this time Stuanswerarr the data in the foreground Stuanswerarr,     return content (re.
ToString ()); }




method Two: JS analog form for post submission

1 Client JS code:

FUNCTION&NBSP;REV_SUBMITSTUANSWERSBTN ()  {    var stuanswerarr=json.stringify ( Getqas ());//Convert to JSON string     //js mock post submit     var revqform =
 document.createelement ("form");
    revqform.setattribute ("Method",  ' POST ');     revqform.setattribute ("Action",  ' ...)
/paper/getrevpaper ');
    REVQForm.innerHTML =  "";
    var stuanswerinput = document.createelement ("input");
    stuanswerinput.setattribute ("type",  "hidden");     stuanswerinput.setattribute ("name",  ' Revq ');//' Revq '     
Stuanswerinput.setattribute ("value",  stuanswerarr);
    revqform.appendchild (Stuanswerinput);
    document.body.appendchild (Revqform);
    revqform.submit (); }




2 server-side C # code: transmission in JSON string

Public ActionResult Getrevpaper ()
{
bool re = false;
String Stuanswerjson = request["Revq"] = = null? "": request["Revq"];//' revq '
//deserializing JSON string
list<stuanswerentity> studentanswerlist = jsonconvert.d    Eserializeobject<list<stuanswerentity>> (Stuanswerjson);
Return Content (re. ToString ());
}






the Jquery Ajax Delivery Object (array) implements a work experience list feature in the background and resolved implementation

Project, dynamically added, and data needs to be passed to the background. This takes into account the user experience: The interface is more interactive, multiple additions and deletions are implemented with JS. So, finally pass data to backstage, I also use jquery Ajax method, read JS cache data (array), passed to Ashx.

Here's the problem: jquery passes objects/arrays, cannot be delivered, and the server cannot get the data.

Complete Solution:

1, JS object creation: because the object JSON needs to be serialized before it can be passed to the background, the background is deserialized from the JSON string.

requires that you create an object in JS that is consistent with the entity object in the background C #.

function workex (depart, title, begintime, endtime)  {    this.
suid = 0;     this.
id = 0;     this.
departmentname = depart;     this.
title = title;     this.
begintime = begintime;     this.
endtime = endtime;     this.
description =  "";     this.
enable = 0;
    return this; }

The



Workex object, exactly the same as the C # object.

2, configuration of the jquery   $.ajax method

needs to be modified for the configuration parameters of the $.ajax method:

1) dataType: "JSON ", Traditional:true: The data type must be JSON. By default, traditional is false, that is, jquery will deeply serialize the parameter object to fit the PHP and Ruby on Rails framework,
But the Servelt API cannot handle, and we can set the traditional True to prevent depth serialization

2) This is the point! The JS object needs to be JSON serialized, otherwise it cannot be delivered to the server.

Data: {  Wl:JSON.stringify (worklist)}

3) Complete code:

var ajaxurl =  ". /..
/service/sp.ashx "; $.ajax ({      type:  "POST"     dataType:  "JSON",  Traditional:true,     data: { wl: json.stringify (WorkList)  },      url: ajaxurl,     success: function  (data, textstatus )  {        if  (data != null)  {                             if  (data)  {                 alert ("added successfully, the system will jump to the details interface.")
");                 
window.location.href =  "suspectlist.html";            &nBSP;}             else {                   $ ("#btnAdd"). attr ("Disabled"),
 false);  $ ("#btnAdd"). Text ("resubmit");             }               },     complete: function  (XMLHttpRequest,
 textstatus)  {    ,     error: function  (e)  {                    $ (
"#btnAdd"). attr ("Disabled",  false);  $ ("#btnAdd"). Text ("Try submitting again");     }});



3, on the server side of the deserialization:

1 Gets the data to post: string worklist = Customresponse.getresponse ("Wl");

2) Deserialization:

list<suspectworkexperience> listwork = new list<suspectworkexperience> ();
Listwork = newtonsoft.json.jsonconvert.deserializeobject<list<suspectworkexperience>> (worklist);

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

Newtonsoft.json is an open source Json format serial number and a deserialized class library under. NET.
Official website: http://json.codeplex.com/


The use of the method is relatively simple

1. First download the version you want, and then refer to the Newtonsoft.Json.dll file in your application.



2. Referencing namespaces



This can be directly converted to the background of the entity.

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.