从MVC控制器返回JSON字符串 [英] return JSON string from MVC controller

查看:602
本文介绍了从MVC控制器返回JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的code发送/接收对象到我的MVC控制器:

I use the following code to send/receive an object to my mvc controller:

$.ajax({
url: _createOrUpdateTimeRecord,
data: JSON.stringify(data),
type: "POST",
//dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
    $("#loading-overlay").show();
},
success: function (data2) {
    try {   // tried to parse it manually to see if anything changes.
        data2 = JSON.parse(data2);
    }
    catch (err) {

    }
},
error: function (xhr, ajaxOptions, thrownError) {
    alert(thrownError + 'xhr error -- ' + xhr.status);
}

});

在我的MVC控制器我有我的JSON对象的字符串,所以我不需要.NET的JavaScriptSerializer和JsonResult。

On my mvc controller I have my JSON object as string so I don't need the .NET JavascriptSerializer and JsonResult.

我的JSON字符串如下:

My JSON string looks like:

data2 = "{title:'1111111',start:'2014-03-23T16:00:00.000',end:'2014-03-23T18:00:00.000',id:107,hdtid:1,color:'#c732bd',allDay:false,description:''}"

和我总是得到:
无效字符

And I always get: "Invalid character"

我已经尝试返回一个字符串,然后手动解析JSON的客户端。因此,我用ContentResult类型的返回类型,但没有成功。

I already tried to return a string and parse the JSON manually on client side. Therefore I used ContentResult as return type but with no success

    public class JsonStringResult : ContentResult
    {
        public JsonStringResult(string json)
        {
            Content = json;
            ContentType = "application/json";
        }
    }

这里有什么问题吗?该JSON看起来很好...

What is the problem here? The JSON looks fine...

干杯,
斯特凡

Cheers, Stefan

推荐答案

您DATA2是的无效 JSON字符串。它应该是:

Your data2 is INVALID JSON string. It should be:

data2 = "{\"title\":\"1111111\",\"start\":\"2014-03-23T16:00:00.000\",\"end\":\"2014-03-23T18:00:00.000\",\"id\":107,\"hdtid\":1,\"color\":\"#c732bd\",\"allDay\":false,\"description\":\"\"}"

在这里阅读JSON标准 http://json.org

JSON比普通的JavaScript更加严格,密钥必须用双引号和字符串在双引号被包裹得,单引号是无效的。

JSON is more strict than plain javascript, key has to be wrapped in double quote, and string has to be wrapped in double quote too, single quote is invalid.

道格拉斯Crockford的JSON设计的严格的格式的原因。 http://www.yuiblog.com/blog/2009/ 8月11日/视频克罗克福德-JSON /

Douglas Crockford designed strict format of JSON for reasons. http://www.yuiblog.com/blog/2009/08/11/video-crockford-json/

他的主页上有很多有价值的链接了。 http://javascript.crockford.com

His home page has many valuable links too. http://javascript.crockford.com

这篇关于从MVC控制器返回JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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