wayfarer
wayfarer

Reputation: 790

Send somewhat complex object via JQuery AJAX to MVC Controller

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

Upvotes: 0

Views: 2622

Answers (1)

wayfarer
wayfarer

Reputation: 790

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

Upvotes: 2

Related Questions