Dimi Dimi - 4 months ago 14
Ajax Question

ApiController method with multiple parameters

It is unclear from here http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
how to use multiple parameters with ApiController method and what is the URL to call it as well. Any clue?

C#

[RoutePrefix("api/workorders")]
public class WorkOrdersController : ApiController
{
[Route("WorkOrdersByDates")]
[HttpGet]
public IEnumerable<WorkOrderItemView> GetWorkOrdersByDates(string startDate, string endDate)
{
var r = new List<WorkOrderItemView>();
//
return r;
}
}


AJAX

var startDate = $('#StartDate').val();
var endDate = $('#EndDate').val();

$.ajax(
{
url: "api/workorders/WorkOrdersByDates",
type: "GET",
contentType: "application/json",
data: JSON.stringify({ startDate: "' + endDate + '", endDate: "' + endDate + '" }),
success: function (result) {
alert(result.Result);
}
});


Global.asax

protected void Application_Start()
{


RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);


AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Answer

You shouldn't be using JSON.stringify for those parameters as that will pass a string to the data parameter, just give it the raw object itself and let jQuery convert them to a query string.

var startDate = $('#StartDate').val();
var endDate = $('#EndDate').val();

$.ajax(
    {
        url: "api/workorders/WorkOrdersByDates",
        type: "GET",
        contentType: "application/json",
        data: { startDate: "' + endDate + '", endDate: "' + endDate + '" },
        success: function (result) {
            alert(result.Result);
        }
    });