我有一个表单,用户可以从中向控制器提交序列化值。有一个select2,用户可以从中选择一个或多个员工代码。如何将这些多个代码与其他表单值一起传递给控制器?
发布的数据如下:
"appointmentCode=80814&employees%5B%5D=0387&employees%5B%5D=1055"
视图:
<form id="appointmentForm">
<div class="modal-body">
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md small">
<div class="form-group">
<label for="appointmentCode">Appointment Code</label>
<input name="appointmentCode" type="text" class="form-control" id="appointmentCode" placeholder="">
</div>
<div class="form-group">
<label for="employeeCode">Scheduled Employees</label>
<select class="js-example-basic-multiple" name="employees[]" id="selectedEmployeeCodes" multiple="multiple" style="width: 250px">
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button id="buttonSubmit" type="button" class="btn btn-primary" data-dismiss="modal">Save Appointment</button>
</div>
</form>
<script>
$(document).ready(function () {
$('.js-example-basic-multiple').select2();
$('#buttonSubmit').click(function (e) {
e.preventDefault();
var appointmentData = $('#appointmentForm').serialize();
$.ajax({
url: '/Schedule/SetAppointment',
data: appointmentData,
cache: false,
'themeSystem': 'bootstrap',
success: function (results) {
if (results === 'Ok') {
} else {
}
}
});
return false;
});
});
</script>
控制器
public IActionResult SetAppointment(appointments_ALL_v appointments_ALL)
{
// submit data to database
}
型号
public class appointments_ALL_v
{
public string appointmentCode { get; set; }
public string[] employees { get; set; }
}
我试图通过这种方法实现的目标可能吗?我希望能够使用serialize函数,因为它使解析此表单(实际上包含50多个输入字段(变得更加容易。
不确定这是否是最好的方法,但我最终在表单中放置了一个隐藏元素,在提交表单时,该元素将把所有选定的选项值作为逗号分隔的字符串。然后,控制器可以从序列化的表单数据中获得该值,并进行拆分以获得每个员工。
$.each($('#selectedEmployeeCodes').find(':selected'), function (index, value) {
eCodes = value.value + ',' + eCodes;
});
$("#employeeCode").val(eCodes.replace(/,*$/, ""));
var appointmentData = $('#appointmentForm').serialize();
如果有人有更好的解决方案,我很乐意听到!