Passing Arrays of Complex Objects to ASP.NET MVC Controllers
In this scenario, you seek to pass an array of complex objects to a controller action. To achieve this, several steps are necessary.
Preparing the View
The provided code in the question already prepares an array of objects. The key here is to transform this array into a JSON format that can be parsed by the controller. To do this, use the $.toJSON() function from the jQuery library, as seen in the solution's improved view code:
function getplaceholders() { // ... var postData = { widgets: results }; $.ajax({ // ... data: $.toJSON(widgets), // ... }); }
Decorating the Controller Action
For the controller action to accept and process the JSON data, it needs to be decorated with a custom attribute. In this case, we use the JsonFilter attribute:
[JsonFilter(Param = "widgets", JsonDataType = typeof(List<PageDesignWidget>))] public JsonResult SaveOrUpdate(List<PageDesignWidget> widgets)
The Param property specifies the parameter name that will receive the JSON data, and JsonDataType defines the expected data type for deserialization.
Custom Attribute Functionality
The JsonFilterAttribute implementation intercepts the HTTP request and checks if it contains JSON content. If so, it deserializes the JSON into the specified data type using JsonConvert.DeserializeObject from Json.NET and assigns it to the corresponding action parameter.
public class JsonFilter : ActionFilterAttribute { // ... public override void OnActionExecuting(ActionExecutingContext filterContext) { // ... var result = JsonConvert.DeserializeObject(inputContent, JsonDataType); filterContext.ActionParameters[Param] = result; } }
By following these steps, you can successfully pass arrays of complex objects from your view to your ASP.NET MVC controller.
The above is the detailed content of How to Pass Arrays of Complex Objects to ASP.NET MVC Controllers Using JSON?. For more information, please follow other related articles on the PHP Chinese website!