开发者

Send generic JSON data to MVC2 Controller

I have a javascript client that is going to send json-formatted data to a set of MVC2 controllers. The client will format the json, and the controller will have no prior knowledge of how to interpret the json into any model. So, I can't cast the Controller method parameter into a known model type, I just want to grab the generic json and pass it to a factory of some sort.

My ajax call:

function SendObjectAsJSONToServer(object,url,idForResponseHTML) {
    // Make a call to the server to process the object
    var jsonifiedObject = JSON.stringify(object);
    $.ajax({
        url: url // set by caller
            , dataType: 'json'
            , data: jsonifiedObject
            , type: 'GET'
            , error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
            , success: function(data) {
                alert(data.message); // Note that data is already parsed into an object
            }
    });
}

My MVC Controller:

public ActionResult SaveForm(string obj)
{
    // Ok, try saving the object
    st开发者_StackOverflow中文版ring rc = PassJSONToSomething(obj.ToString());
    string message = "{\"message\":\""+rc+"\",\"foo\":\"bar\"}";
    return new ContentResult { Content = message, ContentType = "application/json" };
}

The problem is that obj is always null. Can anyone tell me how I should structure the ajax call and the controller parameter so that I get my json to the server? I'm using MVC2. This may appear to be a duplicate of some SO questions, but in my case I do not know the Model that the json maps to, so I can't use a specific model type in the controller parameter type.

Thanks very much.


Have you tried something like that?

$.ajax({
        url: url // set by caller
            , dataType: 'json'
            , data: {obj :jsonifiedObject}
            , contentType: 'application/json; charset=utf-8'
            , type: 'GET'
            , error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
            , success: function(data) {
                alert(data.message); // Note that data is already parsed into an object
            }
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜