In this post I'll show how to consume an
ASP.Net Web API using
JQuery.
First create two ASP.Net MVC projects. Named them as
Client and
WebAPI. The WebAPI project contains all the API code hat we are going to access via Client. At the end WebAPI content will be published in to
IIS and we will access API via Client.
Add
Make,
Model and
Car classes.
Then add
MakeApiController,
ModelApiController and
CarApiController like below.
At the end, Client page will be look like below.
Depending on selections combo boxes will be filled out. So in
ModelApiConotroller, we need a API method like '
GetModelsByMakeId'. Also in
CarApiController, we need a API method like '
GetCarByModelId'. But the issue is both traditional and verb-based routing cannot be used in the same
ApiController. Already there is a
Get Verb method in both controllers. So change the code in both controllers like below. Commented block is existing Get Verb method.
Now open
IIS and create web application like below. I have used port 86. Publish your WebAPI project to that web application path.
Now we have to develop our Client project. First of all, download
bootstrap and paste the files in to relevant locations.
Create a controller called
CarController and open
Index.chtml of that. Edit the code like below.
Create
Demo.js file in Scripts folder and add relevant code. In the below image you can see how to call Web API resource using
JQuery.
Now run the Client and browser for
Car page.
You can find the source code of this in
GitHub.