您的原始代码看起来没有错。你确定你只得到索引吗?也许您也应该发布您的 MultiSelect 代码。我发现这个问题是因为我遇到了同样的问题并使用了其他答案作为参考,但我发现它们过于复杂。所以让我用另一种复杂的方式回答:)
这就是我所拥有的。我知道它的代码比你需要的多,但我认为在这里看到全貌很重要。首先让我设置一下。如果您多次使用 Kendo().MultiSelect.Name("SomeName") 属性,则会出现问题。 “名称”不仅设置了 html 名称,还设置了 id,并且您永远不希望两个 id 具有相同的标识符。所以在我的代码中,我在 MultiSelect.Name 属性中附加了一个唯一的 ID,以确保一个唯一的 ID。我将 MultiSelect 放在人员表的每一行中。我展示这个以确保您使用 DataValueField 属性,以便您能够获取选定的值(而不是您在 ui 中看到的文本)。如果您只是显示一个没有 id 的文本值列表,也许这就是您得到错误数据的原因?
@foreach (var cm in Model.CaseMembers)
{
<tr>
<td>
@(Html.Kendo().MultiSelect()
.Name("IsDelegateFor" + cm.CaseMemberId)
.Placeholder("is a delegate for..")
.DataTextField("FullName")
.DataValueField("CaseMemberId")
.BindTo(Model.Attorneys)
)
</td>
</tr>
}
然后,稍后,在我的 jQuery 中,我尝试提取 DataValueField (CaseMemberId),它是 MultiSelect 的选定值的数组...
var sRows = [];
$('#cmGrid tr').each(function () {
// 'this' is a tr
$tr = $(this);
// create an object that will hold my array of selected values (and other stuff)
var rec = {};
rec.IsADelegateFor = [];
// loop over all tds in current row
$('td', $tr).each(function (colIndex, col) {
if (colIndex === 3) {
// make sure our MultiSelect exists in this td
if ($(this).find("#IsDelegateFor" + rec.CaseMemberId).length) {
// it exists, so grab the array of selected ids and assign to our record array
rec.IsADelegateFor = $(this).find("#IsDelegateFor" + rec.CaseMemberId).data("kendoMultiSelect").value();
}
}
}
// add this tr to the collection
sRows.push(rec);
}
所以这是一种超级冗长的说法,就像其他人提到的那样,这一行可以完美地获取 id。无需遍历 .value() 数组并将内容推送到另一个数组!
rec.IsADelegateFor = $(this).find("#IsDelegateFor" + rec.CaseMemberId).data("kendoMultiSelect").value();
所以在你的原始代码中,没有理由以下不应该工作,
var multiselect = $("#SelectRoles").data("kendoMultiSelect");
var selectedData = [];
selectedData = multiselect.value();
console.log(selectedData);
除非
- 您没有在 C# 中使用 DataValueField 正确设置 MultiSelect
- 您在页面上有多个具有完全相同 id 的 MultiSelects,并且它读取的内容与您想象的不同。
- 您甚至没有值字段,只有一个文本列表。