Ajax call to MVC project


I have a webforms project and I am attempting to add a separate MVC WebApi project to my solution to handle ajax calls.  

I would like to be able to make an ajax call from a javascript file that is loaded into the main .aspx page of the webforms project to
some Api Controller in the MVC project

And have data returned back to the client side

Is this possible?

Here is my current code:

type: "GET",
url: "/RestService/Controllers/CustomerController2",
data: JSON.stringify(jsonArgs),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//code here doesn’t get called

public string GetCustomersByQuery(string searchFor, string searchQuery, string orderBy, string direction, int limit, int offset)
//code here doesn’t get called

I’m not particularly familiar with webAPI, but shouldn’t your action be part of the url option in your ajax request?

url: "/RestService/Controllers/CustomerController2/GetCustomersByQuery",

You appear to be targeting the URL of the Controller itself and not a particular method within the Controller. You’ll likely want to include the name of your method within the URL that you are targeting :

url: "/RestService/Controllers/CustomerController2/GetCustomersByQuery",

If you continue to have issues targeting this method, I would recommend using the Developer Tools (F12) within your browser and checking the Console, which you display any errors that might be related to your service not being properly called.

Thanks for the replies, but I tried that too, along with a bunch of other variations of url’s and no luck. I think its because the controller was in a separate project, so maybe I have to change something in the web.config or references so the ajax call
can see where it has to go? But I think I’m giving up on this method and going to try something a little simpler that doesn’t include another project in the solution, maybe an HTTP handler

It may be an issue of it being a relative URL as well. You might try to specify the name of the project as well prior to your existing URL and ensure that your service project is actually running alongside of your MVC existing project : 

url: "YourServiceProject/RestService/Controllers/CustomerController2/GetCustomersByQuery",


Try after making following changes

1) Please add following entry in WebApiConfig.cs
     config.Routes.MapHttpRoute("DefaultApiWithAction", "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
2) Change url to
 url: "/RestService/api/Customer/GetCustomersByQuery"

Leave a Reply