I am having problems getting json values โโfrom my javascript / jQuery request for my controller.
MyClass is as follows:
function MyClass() { this.MyString = null; this.MyInt = null; this.Subs = null; }
My request is as follows:
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 as in my "MyClass" class. But there are no values โโin myObj.
Where is the problem. Is there anything I can do to correctly display this display?
Thank you very much,
Chris
UPDATE:
Thank you for your cues. I used the JavascriptSerializer. But I have a 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 meaning? Should I accept the value from the request data?
@Dave Ward
The second solution works. But I have a problem with submarines.
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 they are all empty. What can I do?
@Dave Ward, @ALL
Using traditional settings, my 10 Subs bot is empty, they are not there. Counting count is 0 (not NULL). I tried changing the type of Subs from a list to IEnumerable, but that didn't help. Do you know anything else I can do to get Subs populated by my controller?
Ok, thanks Dave Ward, I will use the JSON method.
For someone else having the same problem, this controller code can be obtained with:
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(myString)); var serializer = new DataContractJsonSerializer(typeof(MyClass)); MyClass se = serializer.ReadObject(ms) as MyClass; ms.Close();