从MVC控制器返回JSON字符串

时间:2014-03-20 09:34:25

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

我使用以下代码将对象发送/接收到我的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看起来很好......

干杯, 斯蒂芬

2 个答案:

答案 0 :(得分:5)

试一试 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");
 });

答案 1 :(得分:3)

您的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更严格,密钥必须用双引号括起来,字符串也必须用双引号括起来,单引号无效。

道格拉斯·克罗克福德设计了严格的JSON格式。 http://www.yuiblog.com/blog/2009/08/11/video-crockford-json/

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

相关问题