0

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Your suggestion is really excellent one, Thank a lot @Darin Dimitrov.
By doing as you suggested, I no need to use Newtonsoft.Json api.
@Frank, yes, you are correct. If you use ASP.NET MVC 3 you don't need to use anything. The JSON value provider factory is built-in. And if you are using an older version you will need to implement a custom factory which could be done with either the JavaScriptSerializer class as shown in Phil Haack's article or Json.NET if you prefer.
Thank for your giving me knowledge a lot, @Darin.
0

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)
   {
     ....

1 Comment

Thank @labroo, I have changed my code as you suggested. After that, public ActionResult Submit(IEnumerable<Seminar_Detail> result) method do not fire. I mean , when i click submit button my code not go to server - site. Could you please suggest me how. Thank

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.