Reputation: 4244
I am setting up a simple MVC project as I want to expand my knowledge outside of the scope of Umbraco where I usually do this sort of project.
I am familiar with WebApi but cannot seem to get it to work in this instance.
I have a datepicker in my view that is initialised with the following Javascript:
$('#id-tour_0').datepicker({
changeMonth: true,
changeYear: true,
showOn: "button",
buttonImage: "Content/themes/base/images/icon_calendar.gif",
buttonImageOnly: true,
onSelect: function (date) {
$.ajax({
url: '/api/tour/requesttours',
type: 'POST',
data: JSON.stringify(date),
dataType: 'json',
success: function (data){
console.log(data);
}
});
}
});
This then posts to the following WebApi method upon making a selection in the datepicker:
public class TourController : ApiController
{
[System.Web.Http.AcceptVerbs("GET", "POST")]
public string RequestTours([FromBody] String request)
{
return request;
}
}
With my WebApiConfig.cs setup as follows:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
However, when I breakpoint my WebApi method I can see that request is coming up as null. Why is this and how can I get it to receive the value that is posted by my Javascript?
N.B. I have checkeed in Firebug and the correct date is being posted correctly to the method
Upvotes: 0
Views: 869
Reputation: 4244
I ended up doing the following:
$('#id-tour_0').datepicker({
changeMonth: true,
changeYear: true,
showOn: "button",
buttonImage: "Content/themes/base/images/icon_calendar.gif",
buttonImageOnly: true,
onSelect: function (date) {
$.ajax({
url: '/api/tour/requesttours',
type: 'POST',
data: {Date: date},
dataType: 'json',
success: function (data){
console.log(data);
}
});
}
});
Then I created a new object in my C# code that I mapped the request parameter to:
public class TourController : ApiController
{
public string RequestTours([FromBody] DateRequest request)
{
return request.Date;
}
}
public class DateRequest
{
public string Date { get; set; }
}
Upvotes: 0
Reputation: 8950
Post parameter name should map to the name of the function argument in your class file
So create a object like this
var dateX = new Object();
dateX.request = date.Date;
Then send this object in your ajax call
data: JSON.stringify(dateX),
or directly pass the object like this
data: '{request:"'+ date.Date +'"}'
Upvotes: 2