I’m trying to serialise my form, but for some reason I can’t make it work. The serialisation of the form is working. But the issue is, that I’ll need to add a list afterwards, since it’s not a part of the form, and when doing this my model is NULL when it’s hitting my controllers endpoint.
var valdata = $("#CreateForm").serialize();
var elements = document.querySelectorAll('#productCheckbox:checked');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
return el.name;
});
if (checkedElements.length == 0) {
alert('You must select at least one product');
return
}
var data = {
model: valdata,
products: checkedElements
};
$.ajax({
url: '/Product/Create',
type: 'post',
dataType: 'json',
data: data,
success: function (data) {
console.log('Success: ' + JSON.stringify(data))
},
error: function (data) {
console.log('Error: ' + JSON.stringify(data))
}
});
The function of the Controller I’m hitting:
public ActionResult Create(Model model, object products)
The object products is working fine, but the model is null
.
Do anyone have any suggestions, how to fix this? 🙂
Please don’t mind the name of the objects like Model, this is named something else in our project.
2
Answers
The "data" parameter is just a URL encoded string. You can append to it however you like.
For Example:
Check the below link for more details.
Click here for more details
Here is a demo:
Model:
View:
js(I convert form data to a model):
result: