I have problems to receive json values from my javascript/jQuery request to my controller.
MyClass looks like the following:
function MyClass() {
this.MyString = null;
this.MyInt = null;
this.Subs = null;
}
My Request looks like the following:
var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
var testData2 = new MyClass();
testData2.MyInt = 5678;
testData2.MyString = "GHIjkl";
testData1.Subs.push(testData2);
var jsonData = JSON.stringify(testData1);
var self = this;
$.ajax({
url: '/Home/Request',
type: 'POST',
dataType: 'json',
data: jsonData,
contentType: 'application/json; charset=utf-8',
success: function (x) {
self.ParseResult(x);
}
});
Now I have a controller:
public JsonResult Request(MyClass myObj)
{
var answer = ...
return Json(answer, JsonRequestBehavior.DenyGet);
}
With the following class:
public class MyClass
{
public string MyString { get; set; }
public int MyInt { get; set; }
public List<MyClass> Subs { get; set; }
}
All names in jsonData are exactly the same like in my class "MyClass". But there are no values in myObj.
Where is the Problem. Is there anything I can do to get this mapping working correctly?
Thank you very much in advance,
Chris
UPDATE:
Thank you for your repley. I have used the JavascriptSerializer. But I have the problem, that myString is null:
public JsonResult Data(string myString)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
var data = serializer.Deserialize<MyClass>(myString);
var answer = ...
return Json(answer, JsonRequestBehavior.DenyGet);
}
Where is the value? Should I take the value from the request-data?
@Dave Ward
You second solution is working. But I have a problem with the subs.
var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
for (var i = 0; i < 10; i++) {
var testData2 = new MyClass();
testData2.MyInt = i;
testData2.MyString = "abcDEF";
testData1.Subs.push(testData2);
}
I get 10 Subs in my controller, but all are empty. What can I do?
@Dave Ward, @ALL
Using the traditional settings my 10 Subs are bot empty, they are not there. Subs count is 0 (not NULL). I tried to change the Subs Type from List to IEnumerable but that didn't help. Do you know anything else I can do to get Subs filled in my controller?
Ok, thank you Dave Ward, I will use the JSON method.
For somebody else having the same problem this controller code could be from help:
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(myString));
var serializer = new DataContractJsonSerializer(typeof(MyClass));
MyClass se = serializer.ReadObject(ms) as MyClass;
ms.Close();