0

I got the AJAX send/receive cycle to work sending a string code and receiving a complex Json object, which I then can do many things with. In terms of sending more complex data back to the server, I've read many posts on this topic and have not been able to figure out how to make this happen.

So I built the below, hoping to get some feedback. In a previous version I got it to push a complex object through to the controller, but didn't have enough structure in C# to make use of it. So I shifted a fixed structure (a command code plus an array of key value pairs). However, in this version, it fails on the ajax send.

JavaScript

//=============================
KeyValueObject = new function () {  
    this.key
    this.value
}
//=============================
AjaxSendObject = new function () {
    this.code
    this.data
}
/

/=============================
function JSTest() {
wrkData = BuildAjaxSendKV()
AJAX_Client_Sender("datasendtest",wrkData)
}
//=============================
function BuildAjaxSendKV() {  // build an array of key value objects
    wrkAR = []
    wrkKV = KeyValueObject
    wrkKV.key = "name"
    wrkKV.value = "XYZ"
    wrkAR.push(wrkKV)

    wrkKV = KeyValueObject
    wrkKV.key = "title"
    wrkKV.value = "ABC"
    wrkAR.push(wrkKV)

    return wrkAR
}
//=============================
function AJAX_Client_Sender(ajaxRequestType,varSendKV) {   
    $.ajaxSetup({ cache: false });
    var wrkjson = varSendKV
    var wrkData = CreateJsonSendData(ajaxRequestType, varSendKV)
    a=1
    $.ajax({                          // fails here, doesn't like the data
        type:"POST",
        url: "/Main/AJAX_Router",
        data: {receiver:wrkData},
        datatype: 'json',
        success: function (msg) {
            if (msg.indexOf("ok") == -1) {
                var json = $.parseJSON(msg)
                wrkjson = json
            }
            //var a = json["1"].MainText
            AjaxClientRouter(ajaxRequestType, wrkjson)
        },
        error: function (request, status, error) {
            alert(request.responseText);
        }
    })
}
//=============================
function CreateAJAXSendData(ajaxRequestType, varSendKV)
{
    var wrkSend = AjaxSendObject
    wrkSend.code = ajaxRequestType
    wrkSend.data = varSendKV
    return wrkSend
}

C#

//=============================
public class AJAXReceiverWrapper
{
public AJAXReceiver receiver { get; set; }
}
//=============================
public class AJAXReceiver
{
public string code { get; set; }
public string[] ar { get; set; }
}
//=============================
public class MainController : Controller
{
//
public class MainController : Controller
{
public ActionResult AJAX_Router(AJAXReceiverWrapper varReceiverWrapper)
{
string code = "";
string wrkObj = "";
try
{
AJAXReceiver wrkReceiver = varReceiverWrapper.receiver;
code = wrkReceiver.code;
}
catch (Exception e)
{
string errmsg = e.Message;
}
// do more stuff
5
  • can you do a console.log for your wrkData, and see if that's a valid JSON being generated. Commented Feb 27, 2014 at 5:28
  • @PrerakK, thnx will try that in am Commented Feb 27, 2014 at 5:40
  • ah,I see it should be ' data:({receiver:wrkData}) ' i.e. needs parentheses Commented Feb 27, 2014 at 12:31
  • Looks like a simple typo, should be data: {jsonString: wrkDataString } (colon, not comma) Commented Feb 28, 2014 at 3:53
  • @Phil, thanks, it was valid json; the error in the AJAX send was actually in the success function; the rest of the problem was in the receiving C# code, where I didn't understand how to parse the incoming data. The C# code I originally posted was such a kludge I didn't see any point in asking people to continue looking at it. Commented Feb 28, 2014 at 3:56

1 Answer 1

2

thanks Prekak K I got this working:

I got this to work, and since there were only a couple of suggestions I thought I would just post the solution. Plus the original code was such a kludge it probably shouldn't have been posted in the first place.

The only really difficult part (other than writing the code carefully!) was getting the complex type to match the structure of the object sent from the client, but that relies on post-newbie understanding of JavaScript and C# (or in my case, trial and error...)

JavaScript

//=============================
KeyValueObject = new function () {  
    this.key
    this.value
}
//=============================
AjaxSendObject = new function () {
    this.code
    this.data
}
/

/=============================
function JSTest() {
wrkData = BuildAjaxSendKV()
AJAX_Client_Sender("datasendtest",wrkData)
}
//=============================
function BuildAjaxSendKV() {  // build an array of key value objects
    wrkAR = []
    wrkKV = KeyValueObject
    wrkKV.key = "name"
    wrkKV.value = "XYZ"
    wrkAR.push(wrkKV)

    wrkKV = KeyValueObject
    wrkKV.key = "title"
    wrkKV.value = "ABC"
    wrkAR.push(wrkKV)

    return wrkAR
}
//=============================
function AJAX_Client_Sender(ajaxRequestType,varSendKV) {   
    $.ajaxSetup({ cache: false });
    var wrkjson = varSendKV
    var wrkData = CreateJsonSendData(ajaxRequestType, varSendKV)
    wrkDataString = JSON.stringify(wrkData)
    $.ajax({                          
        type:"POST",
        url: "/Main/AJAX_Router",
        data: {jsonString,wrkDataString },
        datatype: 'json',
        success: function (msg) {
            if (msg.indexOf("ok") == -1) {
                var json = $.parseJSON(msg)
                wrkjson = json
            }
            //var a = json["1"].MainText
            AjaxClientRouter(ajaxRequestType, wrkjson)
        },
        error: function (request, status, error) {
            alert(request.responseText);
        }
    })
}
//=============================
function CreateAJAXSendData(ajaxRequestType, varSendKV)
{
    var wrkSend = AjaxSendObject
    wrkSend.code = ajaxRequestType
    wrkSend.data = varSendKV
    return wrkSend
}

C#

//=============================
    public class AJAXReceiver
{
    public string code { get; set; }
    public List<KeyValueObject> data { get; set; }
}
 //=============================
public class KeyValueObject
{
    public string key { get; set; }
    public string value { get; set; }
}
//=============================
//


 public ActionResult AJAX_Router(string jsonString)
        {
            string code = "";
            var varJSSerializer = new JavaScriptSerializer();
            List<KeyValueObject> wrkKVL = new List<KeyValueObject>();
            try
            {
                var varJSSerializedResult = varJSSerializer.Deserialize<AJAXReceiver>(jsonString);  

                code = varJSSerializedResult .code;
                    wrkKVL = varJSSerializedResult .data;
            }
            catch (Exception e)
            {
                string errmsg = e.Message;
            }
            //--------------------------------------------
            switch (code)
    // do more stuff
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.