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
- 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));
}