Reputation: 18859
I have an MVC web application, with this model
public class PersonViewModel
{
public Guid SchoolId { get; set; }
public string Name { get; set; }
}
public class StudentViewModel : PersonViewModel
{
}
I have this controller method to take a StudentViewModel and create a Student in my database:
[HttpPost]
public async Task<IActionResult> CreateStudent(StudentViewModel viewModel)
{
// ... do stuff
}
I'm doing a lot of dynamic UI stuff with my form, and I might be posting to different endpoints with different values, so I decided to just submit the form using javascript and decide where I'm posting to based on some conditionals.
So that's basically the reason I'm not going the normal route with the strongly typed helper methods - this is what I have in my view:
<form id="form">
<input name="SchoolId" value="@Model.Id" type="hidden" />
<input name="Name" type="text" />
<button type="submit">Create</button>
</form>
<script>
$(document).ready(function () {
$('#form').on('submit', function (e) {
e.preventDefault();
var formData = $('#form').serialize()
console.log(formData);
$.ajax({
url: '/CreateStudent',
type: "POST",
data: formData,
contentType: "application/json"
});
});
});
</script>
I can see in my console log that the form data is serialized correctly, and it hits my controller method. But the view model parameter doesn't have the values that I passed to it.
I've tried setting the form data this way:
var formData = JSON.stringify($('#form').serializeArray());
I even tried just hardcoding the values:
var formData = '{"SchoolId":"c65fc8ad-7ad2-e811-b37f-9cb6d0b709c2","Name":"Testing"}';
But no matter what I try, the view model values don't get set.
Am I formatting the form data wrong? Or is there a different way completely that I need to do this?
Upvotes: 1
Views: 10640
Reputation:
When you use .serialize()
, it generates the data in a 'query string' format - i.e. SchoolId=someValue&Name=AnotherValue
, which needs to be sent using the default contentType
which is 'application/x-www-form-urlencoded; charset=UTF-8'
, not as JSON.
Either remove the contentType
option or specify contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
$('#form').on('submit', function (e) {
e.preventDefault();
var formData = $('#form').serialize()
$.ajax({
url: '@Url.Action("CreateStudent")', //recommended
type: "POST",
data: formData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8' // optional
});
});
Note that if you were to use contentType: "application/json"
, then you would generate the data using (assumes you give the inputs the appropriate id
attribute)
var formData = JSON.stringify({
SchoolId: $('#SchoolId').val(),
Name: $('#Name').val(),
})
Upvotes: 7