Views/Home/ComicsAPI.cshtml


@{
  ViewBag.Title = "ComicsAPIView"
  Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container container-fluid">
  
  <div class="col-sm-12">
    <div class="row">
      <div class="col-sm-2">
      </div>
      <div class="col-sm-8">
        <div class="well">
          <div class="text-center">
            <h2>
              Calling an API</h2>
          </div>
          This is an elementary example of an API call within an MVC project. The Home controller
          has an ActionResult function that returns a View referencing this very page. This
          markup contains a $.getJSON(uri) call to the ComicsAPIController which is actually
          just a seperate Controller in the MvcBootstrap project. 
        </div>
        <div>
          <input type="text" id="comicId" size="15" />
          <input type="button" class="btn btn-info" value="Search by ID or Title" onclick="find();" />
          <p id="comic" />
        </div>
        <div>
          
          <ul id="foundComics" style="list-style-type: none" />
        </div>
        <div>
          <h2>
            All Comics</h2>
          <ul id="allComics" style="list-style-type: none" />
        </div>
      </div>
    </div>
    <div class="col-sm-2">
    </div>
  </div>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
  var uri = '';

  $(document).ready(function () {
    document.getElementById("comicId").focus();

    // Send an AJAX request
    $.getJSON(uri)
          .done(function (data) {
            // On success, 'data' contains a list of comics.
            $.each(data, function (key, item) {
              // Add a list item for the comic.
              $('<li>', { text: formatItem(item) }).appendTo($('#allComics'));
            });
          });
  });

  function formatItem(item) {
    return item.ID + " " + item.Title + ': #' + item.Issue;
  }

  function find() {
    var id = $('#comicId').val();

    $.getJSON(uri + '/' + id)
          .done(function (data) {
            $("#foundComics").html("");
            $.each(data, function (key, item) {
              // Add a list item for the comic.
              $('<li>', { text: formatItem(item) }).appendTo($('#foundComics'));
            });
          })
          .fail(function (jqXHR, textStatus, err) {
            $('#comic').text('Error: ' + err);
          });

    document.getElementById("comicId").focus();

  }
</script>