0

When I debug in javascript I see the value of $("#widgetIds").val() is an array of int values such as [1,2,3,4]. When it hits the controller the widgetIds List is null. I have tried:

  • Using .serialize() and .serializeArray() in javascript
  • Changing the widgetIds type to a List<string> on the controller
  • Changing the widgetIds type to an int[] on the controller
  • Changing the widgetIds type to a string[] on the controller
  • Hours of little tweaks that didn't work or made things worse
  • Google
  • Yelling at my monitor
  • Slamming my fist on my desk
  • Beer

NOTE: I'm using this multiselect control. The reason for the optgroups is for separation in the multiselect.

JavaScript

function ProcessButtonClick(){
$.post(processWidgetsUrl, { widgetIds: $("#widgetIds").val() });
}

View

<select id="widgetIds" name="widgetIds" multiple="multiple">
    <optgroup label="Big Widgets">
        @foreach (var widget in Model.Widgets.Where(d => d.WidgetCategoryId == 1))
        {
            <option value="@widget.Id">@widget.DisplayName</option>
        }
     </optgroup>

     <optgroup label="Little Widgets">
         @foreach (var widget in Model.Widgets.Where(d => d.WidgetCategoryId == 3))
         {
             <option value="@widget.Id">@widget.DisplayName</option>
         }
     </optgroup>

     <optgroup label="Red Widgets">
         @foreach (var widget in Model.Widgets.Where(d => d.WidgetCategoryId == 4))
         {
             <option value="@widget.Id">@widget.DisplayName</option>
         }
     </optgroup>

     <optgroup label="Blue Widgets">
         @foreach (var widget in Model.Widgets.Where(d => d.WidgetCategoryId == 5))
         {
             <option value="@widget.Id">@widget.DisplayName</option>
         }
     </optgroup>

     <optgroup label="Round Widgets">
         @foreach (var widget in Model.Widgets.Where(d => d.WidgetCategoryId == 6))
         {
             <option value="@widget.Id">@widget.DisplayName</option>
         }
     </optgroup>

     <optgroup label="Square Widgets">
         @foreach (var widget in Model.Widgets.Where(d => d.WidgetCategoryId == 7))
         {
             <option value="@widget.Id">@widget.DisplayName</option>
         }
     </optgroup>
 </select>

Controller

public virtual ActionResult ProcessWidgets(List<int> widgetIds)
{
    return Json(_widgetComponent.DoStuff(widgetIds));
}
Four_0h_Three
  • 592
  • 10
  • 27

1 Answers1

1

You need to tell the server that you are sending it Json, then ASP.NET MVC will know how to properly interpret the data before it sends it to the controller:

function ProcessButtonClick(){
  $.post(processWidgetsUrl, { widgetIds: $("#widgetIds").val() }, null, "json");
}

You might need to convert your array to proper JSON How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Community
  • 1
  • 1
Bassam Mehanni
  • 14,796
  • 2
  • 33
  • 41