Home >Backend Development >C++ >How to Post an Array of Complex Objects to an ASP.NET MVC Controller Using JSON and jQuery?
Posting Arrays of Complex Objects with JSON and jQuery to an ASP.NET MVC Controller
Problem:
How can an array of complex objects be passed to an ASP.NET MVC controller action, and what parameters should the controller action accept?
Controller Action Method:
The controller action method should have a parameter of type IList
Client-Side Code:
Using jQuery, convert the array of objects into a JSON string and send it to the controller via an AJAX request with the correct data type and content type headers.
Client-Side Code - Enhanced:
For better handling of the JSON content, use the Json.NET library and set JsonDataType to the type of the array to deserialize. This allows the ASP.NET MVC action to directly bind to the deserialized object without manual parsing.
ASP.NET MVC Controller Action Decoration:
Decorate the controller action with a custom attribute like [JsonFilter] to intercept the incoming JSON request and deserialize the correct object into the action parameter.
JsonFilterAttribute Code:
public class JsonFilter : ActionFilterAttribute { public string Param { get; set; } public Type JsonDataType { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.HttpContext.Request.ContentType.Contains("application/json")) { string inputContent; using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream)) { inputContent = sr.ReadToEnd(); } var result = JsonConvert.DeserializeObject(inputContent, JsonDataType); filterContext.ActionParameters[Param] = result; } } }
The above is the detailed content of How to Post an Array of Complex Objects to an ASP.NET MVC Controller Using JSON and jQuery?. For more information, please follow other related articles on the PHP Chinese website!