Frank Myat Thu
Frank Myat Thu

Reputation: 4474

Json DeserializeObject Error return

I have a Javascript function called sendData.

var sendData = function (data) {
        alert("The following data are sending to the server");
        var dataToSend = JSON.stringify(data);
        alert(dataToSend);
        $.ajax({
            type: "POST",
            url: "Submit",
            dataType: "json",
            data: dataToSend,
            contentType: "application/json; charset=utf-8",
            success: function (response, textStatus, jqXHR) {
                alert("success");
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert("fail");
            }
        });
    };

By using this js function, I can see value of dataToSend

[{"Seminar_Code":"CMP04","Speaker":"1","Tag":"1","DateAndTime":""},  {"Seminar_Code":"CMP04","Speaker":"2","Tag":"2","DateAndTime":""},{"Seminar_Code":"CMP04","Speaker":"3","Tag":"3","DateAndTime":""}]

Then I checked it by using http://jsonlint.com/. It is valid.

Then I use below code at Controller Layer.

    [AcceptVerbs(HttpVerbs.Post)]
    //[JsonFilter(Parameter = "seminar_detail", JsonDataType = typeof(Seminar_Detail))]
    public ActionResult Submit(JsonResult Jresult)
    {
        //var ttt = JsonConvert.DeserializeObject(Request["jsonString"], typeof(List<Seminar_Detail>));
        //var result = (new JsonSerializer()).Deserialize<List<Seminar_Detail>>(seminar_detail);
        //var result = JsonConvert.DeserializeObject<List<Seminar_Detail>>(seminar_detail.ToString());

        var result = JsonConvert.DeserializeObject<List<Seminar_Detail>>(Jresult.ToString());
        return View();
    }

Then, I get this error.

JsonReaderException was unhandled by user code
Unexpected character encountered while parsing value: S. Line 0, position 0.

By using Immediate window from vs 2010 IDE --- > Jresult.Data , then I get null.

Result of Immediate window

Jresult.ToString()
"System.Web.Mvc.JsonResult"
Jresult.Data.ToString()
'Jresult.Data' is null
Jresult.Data
null

I am using Newtonsoft.Json and Asp.net MVC 4. Please let me know how to solve this error.

Upvotes: 0

Views: 1545

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

Create a view model:

public class Seminar
{
    public string Seminar_Code { get; set; }
    public string Speaker { get; set; }
    public string Tag { get; set; }
    public string DateAndTime { get; set; }
}

and then have your controller action take a list of this view model as parameter:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Submit(IEnumerable<Seminar> seminars)
{
    ... don't need to use any JSON serializers here. 

    return View();
}

This will work in ASP.NET MVC 3.

If you are using an older version you could create a custom JsonValueProviderFactory as explained in the following blog post and still keep the model in your action.

But in any cases don't put serialization infrastructure code in your controllers. It's not the responsibility of a controller to serialize/deserialize objects.

Upvotes: 3

labroo
labroo

Reputation: 2961

make your controller argument of type string, and then use Newtonsoft.Json to desereialize it.

JSONResult is of type ActionResult and should not be used as an action argument.

also did you first try letting Model Binder deserialize it for you, like

in you ajax call try doing,

data: { 'result': dataToSend } 

and your controller like

public ActionResult Submit(IEnumerable<Seminar_Detail> result)
   {
     ....

Upvotes: 0

Related Questions