1.在视图中定义Select2标签并在表单中包含它:
2.使用jQuery从Select2标签中获取值并将其存储在隐藏字段中:
$('#mySelect2').on('change', function () { // Get selected values var selectedVals = $(this).val();
// Set the value of hidden field
$('#hiddenField').val(selectedVals);
});
3.在表单中包含隐藏字段:
4.在控制器中接收隐藏字段中的值:
[HttpPost] public ActionResult MyControllerAction(MyModel model, string[] hiddenField) { // Process the values // 'hiddenField' contains the selected values from Select2 tag // ... }
注意:在MyControllerAction方法中,必须将隐藏字段的名称作为参数名称,才能从表单中正确地获取其值。