UPDATE
After some more testing, I found the same code below works fine when posting to a regular Controller. In this case the ModelState has values. The issue remains when posting to an APIController.
I am posting to a Web API Controller via JQuery to update data. The update method is working, however the ModelState is always empty and ModelState.IsValid is always true. (I would like to use the ModelState to perform server-side validation of the model properties)
In my view I am using JQuery to post the new object values:
@model MyProject.mvc.ViewModels.ReportsViewModel
using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
@Html.EditorFor(model => model.Report)
<button type="submit" onclick="UpdateObject(); return false;">Update</button>
}
<script type="text/javascript">
function UpdateObject() {
var updatedReport = {
ID: $("#ID").val(),
Name: $("#Name").val()
};
$.ajax({
url: "/api/reports/PutReport",
data: JSON.stringify(updatedReport),
type: "PUT",
contentType: "application/json;charset=utf-8"
});
return false;
}
</script>
And my Web API method is called to perform the update operation:
public HttpResponseMessage PutReport(Report report) { // report object is properly populated here // ModelState has no values and IsValid is always true if (ModelState.IsValid) { // update object } }
Is this the proper way to post to the Web API method? Is there another step required to get the ModelState populated?
Thanks!