I'm facing a challenge with serializing and passing multiple controls inside a div to a controller via AJAX in my view. One of the fields, SchoolType, is a select2 multi-select dropdown.
Model :
public class SchoolModel
{
public string StudentName{ get; set; }
public List<string> SchoolType{ get; set; }
public List<SelectListItem> SchoolTypeList{ get; set; }
}
View :
<div id="divSchool">
<div class="row">
<div class="col-md-12">
<div class="col-md-6">
<div class="form-group">
<label asp-for="SchoolType" class="col-md-3 control-label">School Type</label>
<div class="col-md-9">
<select asp-for="SchoolType" asp-items="Model.SchoolTypeList" class="form-control medium"></select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label asp-for="StudentName" class="col-md-3 control-label">Student Name</label>
<div class="col-md-9">
<input asp-for="StudentName" class="form-control" />
</div>
</div>
</div>
</div>
</div>
</div>
Controller:
[HttpPost]
public ActionResult Index(SchoolModel model)
{
}
My JS Code:
$('#SchoolType').select2({
placeholder: "Filter by school"
}
$("document").on("click", ".btnCheck", function () {
var model = $('#divSchool').find('select, textarea,input').serialize();
$.ajax({
url: "/Student/Index",
type: 'POST',
data: { model: model },
cache: true,
async: true,
}).done(function (result) {
}).fail(function (error) {
})
});
However, when serialized, the values appear like this:
model = "StudentName=Test&SchoolType=1b&SchoolType=26a"
The issue is that while the StudentName value is correct, the SchoolType value appears as null on the server side in the controller. How can I resolve this?
Possible issue: The SchoolType is a list of strings which might be causing it not to map correctly.
EDIT 1: I attempted changing the div into a form but encountered the same problem.
EDIT 2: A solution was found in PHP by modifying the select name. This answer provides an example.