如何使用ajax将json字符串发布到控制器方法? [英] How to use ajax to post json string to controller method?

查看:40
本文介绍了如何使用ajax将json字符串发布到控制器方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够post一个json字符串到一个控制动作,但它总是以null的形式接收字符串.如果我为控制器方法创建一个视图模型,它可以工作,但这不是我想要的,因为要维护的视图模型太多.

I want to be able to post a json string to a control action but it's always receive the string as null. If I create a view model for the controller method, it works, but that's not what I want since there will be too much view models to maintain.

控制器

[HttpPost]
public JsonResult Test(string json){
    // debugger stops here, but json is null. why?
    dynamic item = Json.Parse(json);
    var temp = item.prop1;
    return Json(false, JsonRequestBehavior.DenyGet);
}

javascript

var data = {
    prop1: 'test',
    prop2: 'test2',
};

$.ajax({
    type: 'post',
    dataType: 'json',
    url: 'approot\Test',
    data: JSON.stringify(data),
    contentType: 'application/json',
    success: function(json) {
        if (json) {
            alert('ok');
        } else {
            alert('failed');
        }
    },
});

感谢 Stephen Muecke 的提示,我以这种方式工作:

控制器

[HttpPost]
public JsonResult Test(string json){
    dynamic item = JObject.Parse(json);
    var temp = item.prop1;
    return Json(false, JsonRequestBehavior.DenyGet);
}

javascript

var json = {
    prop1: 'test',
    prop2: 'test2',
};

var data = {
    json: JSON.stringify(json),
};

$.ajax({
    type: 'post',
    dataType: 'json',
    url: 'approot\Test',
    data: data,
    // contentType: 'application/json', <-- no need this.
    success: function(json) {
        if (json) {
            alert('ok');
        } else {
            alert('failed');
        }
    },
});

推荐答案

您的操作方法需要一个字符串.创建一个 javascript 对象,给它属性data"并将你的数据对象字符串化以发送.

Your action method is expecting a string. Create a javascript object, give it the property "data" and stringify your data object to send along.

更新代码:

$.ajax({
    type: 'post',
    dataType: 'json',
    url: 'approot\Test',
    data: { "json": JSON.stringify(data) },
    success: function (json) {
        if (json) {
            alert('ok');
        } else {
            alert('failed');
        }
    },
});

这篇关于如何使用ajax将json字符串发布到控制器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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