Reputation: 1686
I have a view which has multiple controls inside a div which I want to serialize and pass it to the controller via AJAX.The SchoolType field in the view 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 the serialized div appears something like
model = "StudentName=Test&SchoolType=1b&SchoolType=26a"
While these values are right on the client side, on AJAX the StudentName value appears fine whereas the SchoolType value appears as null on the server side in the controller. How do I fix this?
Possible issue: Because the SchoolType value is a List of string, it's not getting mapped to the individual strings.
EDIT 1: I tried to change the div into form but the same issue persists.
EDIT 2: This issue is handled in PHP by changing the select name. This answer shows an example.
Upvotes: 1
Views: 830
Reputation: 1925
While I am not sure you can manipulate the serialization part; you can get that structure manually.
You can serialize other controls like how you are doing using serialize() and assign it to model. And for the Select2, do it this way and add it to the model.
model = {};
$(".select2").each(function () {
var selectedValue = $(this).val();
if (selectedValue != null) {
model[this.name] = selectedValue;
}
});
This will give you the structure you need.
Upvotes: 1