My MVC 4 project includes 2 select
elements with multiple options.
<select id="ReportDetailsSelectList" class="form-control ListBox valid" size="10" multiple="">
<option value="ADMN">Administration</option>
<option value="ARC">Adminstrative Resource Center</option>
<option value="BALS">Balance Sheet</option>
</select>
<select id="ReportDetailsSelectList2" class="form-control ListBox valid" size="10" multiple="">
<option value="ATL">Atlanta</option>
<option value="BALT">Baltimore</option>
<option value="BETH">Betheseda</option>
<option value="CAMD">Camden</option>
</select>
<button id="btnSubmit" name="btnSubmit" type="button" class="btn btn-primary">Submit</button>
The goal is to extract all selected values from the two select
lists and post them using my Action
.
Shown below is the JavaScript code:
$('#btnSubmit').click(function () {
var result = [];
$('select#ReportDetailsSelectList option:selected').each(function () {
var item = {};
item.Key = $(this).val();
item.Value = $(this).text();
result.push(item);
});
var result2 = [];
$('select#ReportDetailsSelectList2 option:selected').each(function () {
var item = {};
item.Key = $(this).val();
item.Value = $(this).text();
result2.push(item);
});
CollectPostData(result, result2);
});
function CollectPostData(result, result2) {
$.ajax({
url: "/Home/GenerateReport",
type: "POST",
data: JSON.stringify({ 'detailList': result, 'detailList2': result2 }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert(data.message);
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occurred!!!");
}
});
}
A simple class structure for storing objects is as follows:
public class DetailList
{
public string Key { get; set; }
public string Value { get; set; }
}
This is followed by the Controller ActionResult:
[HttpPost]
public ActionResult GenerateReport(DetailList[] detailList, DetailList[] detailList2)
{
return Json(new { status = "Success", message = "Success" }, JsonRequestBehavior.AllowGet);
}
However, I encountered a problem in certain scenarios:
1) When multiple options are selected in both lists - data is posted correctly:
2) If there are multiple options in the first list and only one option in the second list - data is posted correctly
3) With one option selected in each list - the first array is null, but the second array is posted correctly:
I'm puzzled as to why this inconsistency exists. Both arrays are collected and posted in the same manner, yet the results vary. When checking with Firefox debugger, I can see that the data is gathered properly. Any assistance on what could be wrong here would be greatly appreciated.