A Comprehensive Guide to POSTing String Arrays to ASP.NET MVC Controller via jQuery

Nov 26, 2025 · Programming · 8 views · 7.8

Keywords: ASP.NET MVC | jQuery | Array Transmission | Model Binding | Traditional Serialization

Abstract: This article provides an in-depth exploration of how to send string arrays from client to server in ASP.NET MVC applications using jQuery's $.ajax method without relying on forms. Based on a highly-rated Stack Overflow answer, it analyzes the critical role of the traditional serialization setting, explains why array parameters receive null values by default, and offers complete code examples with step-by-step implementation details. By comparing problematic code with the solution, it clarifies changes in jQuery serialization behavior and how to properly configure the traditional parameter to ensure array data is correctly parsed by ASP.NET MVC's model binder. Additionally, leveraging principles from ASP.NET Core official documentation on model binding, the article supplements with explanations of data sources, binding mechanisms for simple and complex types, enabling readers to fully understand the data flow from client to server.

Problem Context and Challenges

In ASP.NET MVC application development, there is often a need to send array data from the client to the server, such as IDs of items selected in a multi-select list. An intuitive approach is to use jQuery's $.post method to send the array directly, but developers frequently encounter issues where the controller parameter receives a null value. This is typically due to a mismatch between jQuery's default serialization behavior and the expected format of ASP.NET MVC model binding.

Initial Attempt and Problem Analysis

Suppose we have a front-end function intended to send an array of selected values to the controller's GenerateList action method:

function generateList(selectedValues) {
   var s = {
      values: selectedValues // selectedValues is an array of strings
   };
   $.post("/Home/GenerateList", $.toJSON(s), function() { alert("back") }, "json");
}

The corresponding controller code is as follows:

public ActionResult GenerateList(List<string> values)
{
    // do something
}

Although the data appears to be sent correctly, the values parameter in the controller remains null. The root cause lies in jQuery's serialization method. In earlier versions, jQuery would serialize arrays into the format values=item1&values=item2&values=item3, which aligns with ASP.NET MVC model binding expectations. However, later versions of jQuery changed the default behavior to serialize arrays as values[]=item1&values[]=item2&values[]=item3, adding square brackets. The ASP.NET MVC model binder does not recognize this format, thus failing to bind correctly to the List<string> parameter.

Solution: Enabling Traditional Serialization

To resolve this issue, set the traditional: true option in jQuery's Ajax request to revert to the old serialization behavior. Here is the corrected code example:

function test() {
    var stringArray = new Array();
    stringArray[0] = "item1";
    stringArray[1] = "item2";
    stringArray[2] = "item3";
    var postData = { values: stringArray };
    
    $.ajax({
        type: "POST",
        url: "/Home/SaveList",
        data: postData,
        success: function(data){
            alert(data.Result);
        },
        dataType: "json",
        traditional: true  // Key setting
    });
}

The controller side processes the data accordingly:

public JsonResult SaveList(List<String> values)
{
    return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}

With this configuration, jQuery serializes the data as values=item1&values=item2&values=item3, and the model binder correctly identifies and populates the values parameter. Upon successful execution, the client receives a response containing the first item's value.

In-Depth Understanding of Model Binding Mechanism

ASP.NET MVC model binding is an automated process that extracts data from various sources in an HTTP request—such as route data, query strings, form fields, and the request body—and converts it into parameters for controller action methods or properties of Razor pages. For collection types like arrays or lists, the model binder supports multiple data formats:

When traditional: true is used, jQuery generates the first format, which matches the model binder's default expectation. Without this setting, the generated values[]=... format cannot be directly bound, resulting in a null parameter.

Data Sources and Binding Attributes

The model binder scans data sources in a specific order: form fields, request body (for controllers with the [ApiController] attribute), route data, query string parameters, and uploaded files. For simple types (e.g., strings, integers) and collections, the binder looks for key-value pairs matching the parameter or property name. By using attributes like [FromBody], [FromQuery], etc., developers can explicitly specify the data source. However, when handling JSON request bodies, input formatters (e.g., System.Text.Json) take over data parsing, and binding source attributes may be ignored.

Complete Example and Best Practices

To ensure reliable data transmission, it is recommended to always set traditional: true when sending array data. Below is a complete example demonstrating how to send an array of selected item IDs from the front-end and handle them in the controller:

// Front-end JavaScript
$("#submitButton").click(function() {
    var selectedIds = [];
    $(".itemCheckbox:checked").each(function() {
        selectedIds.push($(this).val());
    });
    
    $.ajax({
        type: "POST",
        url: "/Home/ProcessItems",
        data: { itemIds: selectedIds },
        traditional: true,
        success: function(response) {
            console.log("Items processed:", response);
        },
        error: function(xhr, status, error) {
            console.error("Error:", error);
        }
    });
});

// Back-end C# Controller
[HttpPost]
public JsonResult ProcessItems(List<string> itemIds)
{
    if (itemIds == null || !itemIds.Any())
    {
        return Json(new { success = false, message = "No items selected." });
    }
    
    // Process itemIds, e.g., save to database
    foreach (var id in itemIds)
    {
        // Processing logic
    }
    
    return Json(new { success = true, message = $"Processed {itemIds.Count} items." });
}

Furthermore, for more complex scenarios such as sending nested objects or dictionaries, combining JSON serialization with custom model binders is advisable. However, for simple array transmission, maintaining serialization format consistency with model binding expectations is the most straightforward and effective approach.

Conclusion

By correctly configuring jQuery's traditional parameter, developers can seamlessly send string arrays from the client to an ASP.NET MVC controller, avoiding redundant methods like hidden form fields. Understanding the workings of model binding and the order of data sources aids in debugging and optimizing data flow in more complex situations. This solution is not only applicable to string arrays but can also be extended to other simple type collections, providing a solid foundation for building responsive, data-driven web applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.