【问题标题】:return JSON string from MVC controller从 MVC 控制器返回 JSON 字符串
【发布时间】:2014-03-20 09:34:24
【问题描述】:

我使用以下代码向我的 mvc 控制器发送/接收对象:

$.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。

我的 JSON 字符串如下所示:

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。因此我使用 ContentResult 作为返回类型但没有成功

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

这里有什么问题? JSON 看起来不错...

干杯, 斯蒂芬

【问题讨论】:

    标签: jquery asp.net-mvc json asp.net-mvc-4


    【解决方案1】:

    试一试 Json 控制器

      public JsonResult fnname()
        {
            string variablename = "{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:''}";
            return Json(variablename , JsonRequestBehavior.AllowGet);
        }
    

    Jquery json 传递

     $(document).ready(function() {
       $.post("/controllername/fnname", { }, function (result) {
          alert(result);
       }, "json");
     });
    

    【讨论】:

    • 我想这会导致这里描述的问题:stackoverflow.com/questions/9777731/… 但是,我尝试了该答案的替代方法(反序列化和重新序列化),这对我有用......
    • 对不起,我不知道答案,但什么是反序列化和重新序列化
    • 在这种情况下这是一个超级黑客。我有一个字符串并想返回 JSON。所以我使用 JavaScriptSerializer.deserialize 从我的字符串中获取一个对象,然后我可以创建一个 JsonResult(它隐式使用 JavascriptSerializer)将我的对象再次序列化为 JSON。我不知道为什么,但似乎 JQuery 可以读取此内容,但我不明白为什么它无法读取我的 JSON 字符串……
    • 那么你不要这样做,只需使用 (':') 拆分字符串并制作一个列表,然后再次在 jquery 中我们可以将列表附加为字符串
    【解决方案2】:

    您的 data2 是 INVALID JSON 字符串。应该是:

    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 更严格,key 必须用双引号括起来,string 也必须用双引号括起来,单引号是无效的。

    Douglas Crockford 出于某些原因设计了严格的 JSON 格式。 http://www.yuiblog.com/blog/2009/08/11/video-crockford-json/

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-12
      • 2021-08-14
      • 2015-04-06
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 2011-12-02
      相关资源
      最近更新 更多