I am trying to submit all the items in a select list to an MVC 3 action method. Here is my Action method:
[HttpPost]
public ActionResult SaveList(int SettingID, List<SelectListItem> items)
{
// blah...
}
and here is the simplified version of how I am trying to send the data:
var items = $("#listItems > option").map(function ()
{
var arr = [];
arr.push({ Value: $(this).val(), Text: $(this).text() });
return arr;
}).get();
$.ajax({
type: "POST",
url: "/CompanyAdmin/SaveSettingList/",
dataType: 'json',
data: { items: items, SettingID: SettingID},
success: function (msg)
{
alert(msg);
}
});
The setting ID param gets populated correctly. And the List gets populated with the correct AMOUNT of items, but both the Text and Value properties come out as null.
Do I have to install one of the JSON plugins for jQuery to be able to submit an array of items?
EDIT 1:
Following Darin Dimitrov’s advice I used the stringify method and sent both the SettingID and list of options as JSON.
At first this was not hitting my Action method, so I changed the method to this:
public ActionResult SaveList(SaveSettingListModel json)
{}
with the param being defined like so: (to match the JSON)
public class SaveSettingListModel
{
public int SettingID { get; set; }
public List<SelectListItem> items { get; set; }
}
This now fires the correct method. However, the contents of json on the server side are SettingID = 0 (when I verified that it is 2 on the client side), and items = null.
Try posting them as JSON.
Start by defining a view model:
then modify your controller action to take this view model as argument:
and finally in your script:
And if you want to use the
JSON.stringifymethod in legacy browsers in which it is not natively supported make sure you include the json2.js script.All this being said I see where you are going with this controller action and with this AJAX request and I must say that I wouldn’t do it this way (send the options in the request). I mean in order to render this view you fetched this list from somewhere? Presumably a datastore? So instead of fighting with the HTML
<form>(which sends only the selected value of a dropdownlist to the server when submitted) why don’t you simply use this very same data store in yourSaveListaction in order to fetch those very same options? This will avoid you round-tripping them and save bandwidth. Don’t worry databases are fast. And if they are not in your case simply cache the results of expensive queries.Completely ignore my previous remark if those options are subject to change on the client side and you want to fetch the new values.