我在 Razor View 中使用 Bootstrap 多选下拉列表。提交表单时,我需要将所有选定的值以逗号分隔。但不幸的是,我在发布后获得了 Controller 操作的第一个(唯一一个)值。 这是我的 Razor 代码
@Html.DropDownListFor(m => m.Developer, new SelectList(users, "EmployeeID", "DomainID"), new { @class = "form-control", multiple = "multiple" })
这是我的 JS 代码
$('#Developer').multiselect({
selectAllValue: 'multiselect-all',
enableCaseInsensitiveFiltering: true,
enableFiltering: true,
maxHeight: '300',
buttonWidth: '350',
onChange: function (element, checked) {
var brands = $('#Developer option:selected');
var selected = [];
$(brands).each(function (index, brand) {
selected.push([$(this).val()]);
});
},
onDropdownHidden: function (e) {
$('#Developer').val(selected);
}
});
请注意,“Developer”是我的模型的字符串类型属性
最佳答案
其实很简单:
$('#Developer').val().join(',');
//This creates a comma separated string with the selected values
因此,在您的表单
中,您可以添加一个隐藏输入
,如下所示:
<input type="hidden" name="hiddenChoices" id="hiddenChoices" value="" />
在您的 jquery
代码中:
$('#Developer').multiselect({
selectAllValue: 'multiselect-all',
enableCaseInsensitiveFiltering: true,
enableFiltering: true,
maxHeight: '300',
buttonWidth: '350',
onDropdownHidden: function (e) {
$('#hiddenChoices').val($('#Developer').val().join(','));
//Now the value if hiddenChoices it's like "1,2,3"
}
});
要预先选择值,假设您的值是“1,2,3”
$('#Developer').multiselect('select', "1,2,3".split(','));
关于jquery - 调用 POST 方法时如何获取 Bootstrap 多选下拉列表值作为逗号分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35161544/