I am currently working through Pluralsight training for WebAPI and am running into some issues (downloading the examples didn’t help as they don’t work either – the course was created off of the Beta and I’m using the final version with .Net 4.5). I’ve created a very simple view with the following HTML:
<form onsubmit="return submitCourse();">
<input type="text" name="name" id="name" />
<input type="submit" value="Create Course" />
</form>
<h1 id="msg"></h1>
<script>
//1: have form - get values from form - send to API as json
//2: use form values
function submitCourse() {
//$.ajax({
// url: '/api/courses',
// type: 'POST',
// dataType: 'json'
//});
$.ajax({
url: '/api/courses/',
type: 'POST',
dataType: 'json',
success: function (newCourse) {
var msg = 'New course id = ' + newCourse.id;
$('#msg').text(msg);
}
});
return false;
}
</script>
What is supposed to happen is when the form goes to submit, the script runs first and the form data is transmitted for me via an AJAX call. The problem I’m encountering is when the Post method gets hit in my controller, the “newCourse” parameter is always null:
public Course Post(Course newCourse)
{
newCourse.id = _courses.Count;
_courses.Add(newCourse);
//TODO : return 201
return newCourse;
}
Digging through various tools, I found the script above doesn’t seem to be sending the data at all (content length is 0), however I can’t seem to figure out why (new to WebAPI and jQuery’s $.ajax() call). I’ve tried explicitly setting the body of the call to the form values using the “data” option inside the $.ajax() call (like this: data: { ‘name’ : $(‘#name’).text() }), but that didn’t do much either. The content length seemed to change (to 5, not sure why) but the values still aren’t being deserialized.
Any tips? I’m too new to both of these technologies to know where to start.
You need to post the data to the API using data option inside $.ajax(). You can use data: $(“#CourseForm”).serialize(), if you give the id ‘CourseForm’ to the form and make sure the name of the input fields inside the form matches the property names of Course, for binding to work.