Monday, December 24, 2012

Getting to your WebApi methods in jQuery

I have been working with WebApi in my latest project. If your new to WebApi then this might help you out.

The default api route in Global.asax will look something like,
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

In order for you to be able to call your methods in your WebApi controller you will need to use Url.RouteUrl to build the link correctly.
<script type="text/javascript">
var toUrl = '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "values" , id = "123" })';
$.ajax({
url: toUrl,
type: 'GET',
success: function(result) {
// ...
}
});
</script>

I found a great post on the subject here.

 

If you have any questions feel free to contact me.

No comments:

Post a Comment