I've created an api controller called VisitController
:
public class VisitController : ApiController
{
public class VisitAddModel
{
string VisitId { get; set; }
DateTimeOffset VisitDate { get; set; }
string NoteText { get; set; }
string DoctorNote { get; set; }
}
[HttpPost]
public bool Index([FromBody]VisitAddModel model)
{
return true;
}
}
And I am attempting to POST
data to it via jQuery and AJAX:
var newRec = {
VisitId: 'xxxxxxxxxxxxxxxxxxxx',
VisitDate: '3/27/2018',
NoteText: 'Test note text',
DoctorNote: 'Test doctor note',
_pending: true
};
$.ajax({
url: apiUrl + "/visit",
type: "POST",
data: newRec,
success: function (response) {
if (response && response.VisitId)
previousVisitStore[response.VisitId]._pending = false;
}
});
My controller is getting hit, but every time, no matter what, the model, or the values in the model, are null. I've seen plenty of posts about POST
-ing data to an MVC controller via jQuery, and most talk about adding contentType: "application/json"
, or using JSON.stringify
, or using/not-using [FromBody]
. I have tried EVERY. SINGLE. COMBINATION. of those various configurations (a total of 9 different configuration patterns. And depending on the set of configuration properties, I either see a model with every value null
in my api controller, or, I see a completely null
model in my api controller. I've even checked the F12 tools to see if the values are there in the network traffic. And they are.
I must be overlooking something. What could I be missing here? What do I need to do to ensure my api controller deserializes these values correctly? I am using Asp.Net MVC 5.4. This is my routing, if that might have something to do with it:
public static void Register(HttpConfiguration config)
{
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}