Home >Backend Development >C++ >How Can I Efficiently Pass Complex JSON Arrays from jQuery to ASP.NET MVC Controllers?
JSON and jQuery: Passing Complex Arrays to ASP.NET MVC Controllers
In scenarios where we need to send an array of complex objects to a controller action, it's essential to consider the compatibility between the client-side and server-side code. Let's delve into the approach described by Steve Gentile to resolve this challenge.
Client-Side Processing
The jQuery code:
function getplaceholders() { // Collect data into an array var results = new Array(); ... var postData = { widgets: results }; // Send data to the controller with JSON serialization $.ajax({ url: '/portal/Designer.mvc/SaveOrUpdate', ... data: $.toJSON(widgets), ... }); }
Here, the data is gathered into an array, wrapped within a JSON object, and serialized for transmission to the server.
Controller Action Configuration
The ASP.NET MVC controller action:
[JsonFilter(Param = "widgets", JsonDataType = typeof(List<PageDesignWidget>))] public JsonResult SaveOrUpdate(List<PageDesignWidget> widgets)
The [JsonFilter] attribute customizes the action to receive JSON data. It defines the parameter name ("widgets") and specifies the expected JSON data type (List
Custom JSON Filter Attribute
public class JsonFilter : ActionFilterAttribute { ... public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.HttpContext.Request.ContentType.Contains("application/json")) { // Deserialize JSON data from request body string inputContent = ...; var result = JsonConvert.DeserializeObject(inputContent, JsonDataType); // Assign the deserialized object to the specified parameter filterContext.ActionParameters[Param] = result; } } }
The JsonFilter intercepts requests with JSON content type, deserializes the JSON data using Json.NET's JsonConvert class, and assigns the result to the appropriate action parameter.
By utilizing this approach, we effectively establish communication between the client-side data and the server-side action, allowing the controller to process the complex array of objects received in JSON format.
The above is the detailed content of How Can I Efficiently Pass Complex JSON Arrays from jQuery to ASP.NET MVC Controllers?. For more information, please follow other related articles on the PHP Chinese website!