[Web API] Web API Views

This post shows how to create a simple view to see the result of Web API requests.

 

1. Web API View?

This is not quite right terminology. Web API is a service and not accessed by web in general. But without creating client application, you can test Web API actions in an MVC application.

 

2. Showing Data from GET Request

We are not creating a view from the controller.

You can start from any View and use some JavaScript code. Please look at my previous posts how to create Web API actions.

@{ ViewBag.Title = "APITest"; }
<h2>APITest</h2>
<ul id="videos"></ul>
@section scripts
{
}

Now in the “scripts” section, add the following JavaScript code.

  var productAPI = (function () {
    var getUrl = @Url.RouteUrl("DefaultApi",
new { httproute="", controller = "Products" });
    var getProducts = function () {
      return $.ajax(getUrl);
    };
    return {
     getProducts : getProducts
    }
  }());

  $(function () {
    productAPI.getProducts().done(function (data) {
      $.each(data, function (index, element) {
        $('#videos').append($('<li>', {
          text: element.Id + ': ' + element.Name
        }));
      });
    });
  });

The return data is JSON and automatically deserialized for you.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s