stefan
stefan

Reputation: 1376

return JSON string from MVC controller

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);
}

});

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

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"

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";
        }
    }

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

Cheers, Stefan

Upvotes: 4

Views: 56788

Answers (2)

user1375096
user1375096

Reputation:

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\":\"\"}"

Read JSON standard here http://json.org

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.

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

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

Upvotes: 4

Dinesh
Dinesh

Reputation: 1007

Just Try it Json Conrtroller

  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 passing

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

Upvotes: 6

Related Questions