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.
Create a view model:
and then have your controller action take a list of this view model as parameter:
This will work in ASP.NET MVC 3.
If you are using an older version you could create a custom
JsonValueProviderFactoryas 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.