ASP.NET MVC - How to pass complex objects to a callback Action as callback arguments
This example demonstrates how to convert custom types to a JSON string on the client and parse this string on the server.
The conversion is performed using the $.toJSON
function that is declared in the jquery.json-2.2.min file.
function GetSerializationData() {
var editorsNames = ["Name", "Age", "Email", "ArrivalDate"];
var editorsValues = {};
for (var i = 0; i < editorsNames.length; i++) {
var control = ASPxClientControl.GetControlCollection().GetByName(editorsNames[i]);
editorsValues[control.name] = control.GetValue();
}
return $.toJSON(editorsValues);
}
The JavaScriptSerializer.Deserialize
method parses the JSON string in a Controller's Action.
MyData GetSerializationObject() {
string jsonText = Request.Params["SerializationData"];
if (string.IsNullOrEmpty(jsonText))
return null;
MyData data = null;
try {
data = new JavaScriptSerializer().Deserialize<MyData>(jsonText);
} catch {
ViewData["ErrorMessage"] = "Incorrect data";
}
return data;
}
In this example, if it is not possible to deserialize user input, an exception is thrown.