티스토리 뷰

🌈 .NET MVC

Web APIs

James Wetzel 2018. 6. 1. 11:37

File.cs

public class ProductsController : ApiController

    {

        Product[] products = new Product[]

        {

            new Product { Category = "category1",  Id = 1, Name = "name1", Price = 1 }

            , new Product { Category = "category2", Id = 2, Name = "name2", Price = 2 }

        };


        public IEnumerable<Product> GetAllProducts()

        {

            return products;

        }


        public IHttpActionResult GetProduct(int id)

        {

            var product = products.FirstOrDefault((p) => p.Id == id);

            if (product == null)

            {

                return NotFound();

            }

            return Ok(product);

        }

    }


index.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

  <title>Product App</title>

</head>

<body>


  <div>

    <h2>All Products</h2>

    <ul id="products" />

  </div>

  <div>

    <h2>Search by ID</h2>

    <input type="text" id="prodId" size="5" />

    <input type="button" value="Search" onclick="find();" />

    <p id="product" />

  </div>


  <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>

  <script>

    var uri = 'api/products';


    $(document).ready(function () {

      // Send an AJAX request

      $.getJSON(uri)

          .done(function (data) {

            // On success, 'data' contains a list of products.

            $.each(data, function (key, item) {

              // Add a list item for the product.

              $('<li>', { text: formatItem(item) }).appendTo($('#products'));

            });

          });

    });


    function formatItem(item) {

      return item.Name + ': $' + item.Price;

    }


    function find() {

      var id = $('#prodId').val();

      $.getJSON(uri + '/' + id)

          .done(function (data) {

            $('#product').text(formatItem(data));

          })

          .fail(function (jqXHR, textStatus, err) {

            $('#product').text('Error: ' + err);

          });

    }

  </script>

</body>

</html>

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함