jQuery and ASP.NET MVC: Posting an Array of Complex Objects with JSON
Problem:
How can you pass an array of complex objects to an ASP.NET MVC controller from a jQuery AJAX request? What parameters should the controller action accept?
Solution:
To post an array of complex objects to a controller using jQuery and JSON, follow these steps:
Serialize the array to JSON:
Use JSON.stringify() to convert the array of objects to a JSON string.
Set the request headers:
Specify the Content-Type header to application/json; charset=utf-8.
Use the $.ajax() method:
Create an AJAX request using the $.ajax() method and provide the JSON data as the data parameter.
Controller Action:
Decorate your controller action with a custom attribute (JsonFilter) to deserialize the JSON data. The attribute should specify the parameter name and the JSON data type.
Custom Attribute (JsonFilter):
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; } } }
Example:
JavaScript:
function getplaceholders() { var widgets = []; // ... populate the array $.ajax({ url: '/portal/Designer.mvc/SaveOrUpdate', type: 'POST', dataType: 'json', data: JSON.stringify(widgets), contentType: 'application/json; charset=utf-8' }); }
Controller Action:
[JsonFilter(Param = "widgets", JsonDataType = typeof(List<PageDesignWidget>))] public JsonResult SaveOrUpdate(List<PageDesignWidget> widgets) { // ... }
The above is the detailed content of How to Post an Array of Complex Objects from jQuery to an ASP.NET MVC Controller Using JSON?. For more information, please follow other related articles on the PHP Chinese website!