I was using form serialize() to submit user input data using the ajax post method to the controller in ASP.NET 5 application but data was not passing to the controller. Later on, I have found the solution to this issue. Let's go for the resolution.
Code of ajax post method is,
<script type="text/javascript">
function submitStudent() {
var data = $("#studentForm").serialize();
console.log(data);
alert(data);
$.ajax({
type: 'POST',
url: '/Home/CreateStudent',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
}
</script>
If we are using .serialize() in form submit event,
i.e. $('#yourForm').serialize()
Then we have to remove,
contentType: ‘application/json; charset=utf-8’,
The reason is when we use .serialize() this generates the data in query string format. It needs the default contentType. Default content type is: contentType: ‘application/x-www-form-urlencoded; charset=UTF-8’, so it is optional, you can remove it or can use as depicted in below code.
<script type="text/javascript">
function submitStudent() {
var data = $("#studentForm").serialize();
console.log(data);
alert(data);
$.ajax({
type: 'POST',
url: '/Home/CreateStudent',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // when we use .serialize() this generates the data in query string format. this needs the default contentType (default content type is: contentType: 'application/x-www-form-urlencoded; charset=UTF-8') so it is optional, you can remove it
data: JSON.stringify(data),
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
}
</script>
I hope, you will be able to resolve your form serialization and data sending issue from the user side to the controller.