Home > Backend Development > C++ > How to Pass Arrays of Complex Objects to ASP.NET MVC Controllers Using JSON?

How to Pass Arrays of Complex Objects to ASP.NET MVC Controllers Using JSON?

Susan Sarandon
Release: 2025-01-01 02:28:09
Original
281 people have browsed it

How to Pass Arrays of Complex Objects to ASP.NET MVC Controllers Using JSON?

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),
        // ...
    });
}
Copy after login

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)
Copy after login

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;
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template