【发布时间】:2015-02-12 16:15:23
【问题描述】:
我有我的 MVC 4 项目。我有 2 个select 有多个选项。
<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>
我需要从 2 个select 列表中收集所有选定的值并将其发布到我的Action
这是我的 JavaScript 代码:
$('#btnSubmit').click(function () {
var result = [];
// Go through Details List
$('select#ReportDetailsSelectList option:selected').each(function () {
// Collect Name and Value
var item = {};
item.Key = $(this).val();
item.Value = $(this).text();
result.push(item);
});
var result2 = [];
// Go through Details List
$('select#ReportDetailsSelectList2 option:selected').each(function () {
// Collect Name and Value
var item = {};
item.Key = $(this).val();
item.Value = $(this).text();
result2.push(item);
});
CollectPostData(result, result2);
});
function CollectPostData(result, result2) {
// Post collected data to the action
$.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!!!");
}
});
}
我有一个简单的类来存储我的对象:
public class DetailList
{
public string Key { get; set; }
public string Value { get; set; }
}
这是我的控制器 ActionResult:
[HttpPost]
public ActionResult GenerateReport(DetailList[] detailList, DetailList[] detailList2)
{
return Json(new { status = "Success", message = "Success" }, JsonRequestBehavior.AllowGet);
}
这是我的问题的开始......几个场景:
1) I have multiple option selected in both lists - data posted correctly:
2) Multiple options in 1st list, 1 option in 2nd list - data posted correctly
3) 1 option in 1st list, 1 option in 2nd list - First array is null, but the second array posted correctly:
我不知道为什么会这样?我以完全相同的方式收集我的两个数组并以相同的方式发布它,但由于某些原因,它以不同的方式发布。我检查了 Firefox 调试器,我发现所有数据都收集得很好。 result 和 result2 都有数据,即使只有 1 个项目...
任何人,请帮忙,我在这里做错了什么?
【问题讨论】:
-
我无法重现您的问题,方案#3 对我来说可以正常工作。也许你认为还有其他事情发生?尝试清除浏览器的缓存。
-
我确实清理了缓存...对我不起作用。视图中实际上没有其他任何事情发生。其他日期选择器很少,仅此而已...
-
好的,现在就为我实现。我使用的是 MVC 5,看起来这个问题是 MVC 4 特有的。
标签: javascript arrays ajax json asp.net-mvc