通过jQuery AJAX发送有点复杂的对象MVC控制器 [英] Send somewhat complex object via JQuery AJAX to MVC Controller

查看:90
本文介绍了通过jQuery AJAX发送有点复杂的对象MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了AJAX发送/接收骑车上班发送一个字符串,code和接收一个复杂的JSON对象,然后我可以做很多事情。在发送更复杂的数据到服务器方面,我读过关于这一主题的许多职位,并一直无法弄清楚如何做到这一点。

于是我建立了下面,希望能得到一些反馈。在previous版本,我把它贯穿到控制器推一个复杂的对象,但没有在C#足以结构来利用它。于是我转向固定结构(命令code以及键值对的数组)。然而,在这个版本中,它无法对阿贾克斯发送。

JavaScript的

  // =============================
KeyValueObject =新功能(){
    this.key
    THIS.VALUE
}
// =============================
AjaxSendObject =新功能(){
    这一点。code
    this.data
}
// =============================
功能JSTest(){
wrkData = BuildAjaxSendKV()
AJAX_Client_Sender(datasendtest,wrkData)
}
// =============================
功能BuildAjaxSendKV(){//建立键值对象的数组
    wrkAR = []
    wrkKV = KeyValueObject
    wrkKV.key =名
    wrkKV.value =XYZ
    wrkAR.push(wrkKV)    wrkKV = KeyValueObject
    wrkKV.key =标题
    wrkKV.value =ABC
    wrkAR.push(wrkKV)    返回wrkAR
}
// =============================
功能AJAX_Client_Sender(ajaxRequestType,varSendKV){
    $ .ajaxSetup({缓存:假});
    VAR wrkjson = varSendKV
    VAR wrkData = CreateJsonSendData(ajaxRequestType,varSendKV)
    a = 1时
    $阿贾克斯({//这里失败,不喜欢数据
        键入:POST,
        网址:/主/ AJAX_Router
        数据:{接收器:wrkData},
        数据类型:JSON,
        成功:函数(MSG){
            如果(msg.indexOf(OK)== - 1){
                VAR JSON = $ .parseJSON(MSG)
                wrkjson = JSON
            }
            // VAR一个= json的[1]。的mainText
            AjaxClientRouter(ajaxRequestType,wrkjson)
        },
        错误:功能(请求,状态,错误){
            警报(request.responseText);
        }
    })
}
// =============================
功能CreateAJAXSendData(ajaxRequestType,varSendKV)
{
    VAR wrkSend = AjaxSendObject
    wrkSend。code = ajaxRequestType
    wrkSend.data = varSendKV
    返回wrkSend
}

C#

  // =============================
公共类AJAXReceiverWrapper
{
公共AJAXReceiver接收器{搞定;组; }
}
// =============================
公共类AJAXReceiver
{
公共字符串code {搞定;组; }
公共字符串[] {AR获得;组; }
}
// =============================
公共类MainController:控制器
{
//
公共类MainController:控制器
{
公众的ActionResult AJAX_Router(AJAXReceiverWrapper varReceiverWrapper)
{
字符串code =;
字符串WRKOBJ =;
尝试
{
AJAXReceiver wrkReceiver = varReceiverWrapper.receiver;
。code = wrkReceiver code;
}
赶上(例外五)
{
字符串ERRMSG = e.Message;
}
//做更多的东西


解决方案

感谢prekak K I得到这个工作:

我得到这个工作,而且由于当时只有一对夫妇的建议,我想我会只是张贴了解决方案。加上原来的code是这样,它可能不应该被张贴在首位一个杂牌组装电脑。

唯一真正困难的部分是越来越复杂类型相匹配,从客户端发送的对象的结构,而是依赖于JavaScript和C#新手后的理解((比编写code慎重!除外)或在我的情况,试错...)

JavaScript的

  // =============================
KeyValueObject =新功能(){
    this.key
    THIS.VALUE
}
// =============================
AjaxSendObject =新功能(){
    这一点。code
    this.data
}
// =============================
功能JSTest(){
wrkData = BuildAjaxSendKV()
AJAX_Client_Sender(datasendtest,wrkData)
}
// =============================
功能BuildAjaxSendKV(){//建立键值对象的数组
    wrkAR = []
    wrkKV = KeyValueObject
    wrkKV.key =名
    wrkKV.value =XYZ
    wrkAR.push(wrkKV)    wrkKV = KeyValueObject
    wrkKV.key =标题
    wrkKV.value =ABC
    wrkAR.push(wrkKV)    返回wrkAR
}
// =============================
功能AJAX_Client_Sender(ajaxRequestType,varSendKV){
    $ .ajaxSetup({缓存:假});
    VAR wrkjson = varSendKV
    VAR wrkData = CreateJsonSendData(ajaxRequestType,varSendKV)
    wrkDataString = JSON.stringify(wrkData)
    $阿贾克斯({
        键入:POST,
        网址:/主/ AJAX_Router
        数据:{jsonString,wrkDataString},
        数据类型:JSON,
        成功:函数(MSG){
            如果(msg.indexOf(OK)== - 1){
                VAR JSON = $ .parseJSON(MSG)
                wrkjson = JSON
            }
            // VAR一个= json的[1]。的mainText
            AjaxClientRouter(ajaxRequestType,wrkjson)
        },
        错误:功能(请求,状态,错误){
            警报(request.responseText);
        }
    })
}
// =============================
功能CreateAJAXSendData(ajaxRequestType,varSendKV)
{
    VAR wrkSend = AjaxSendObject
    wrkSend。code = ajaxRequestType
    wrkSend.data = varSendKV
    返回wrkSend
}

C#

  // =============================
    公共类AJAXReceiver
{
    公共字符串code {搞定;组; }
    公开名单< KeyValueObject>数据{搞定;组; }
}
 // =============================
公共类KeyValueObject
{
    公共字符串键{获得;组; }
    公共字符串值{获得;组; }
}
// =============================
//
 公众的ActionResult AJAX_Router(字符串jsonString)
        {
            字符串code =;
            VAR varJSSerializer =新的JavaScriptSerializer();
            清单< KeyValueObject> wrkKVL =新的List< KeyValueObject>();
            尝试
            {
                VAR varJSSerializedResult = varJSSerializer.Deserialize< AJAXReceiver>(jsonString);                。code = varJSSerializedResult code;
                    wrkKVL = varJSSerializedResult。资料;
            }
            赶上(例外五)
            {
                字符串ERRMSG = e.Message;
            }
            // --------------------------------------------
            开关(code)
    //做更多的东西

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

解决方案

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

这篇关于通过jQuery AJAX发送有点复杂的对象MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆