Skip to content

Instantly share code, notes, and snippets.

@abel-masila
Created February 13, 2017 10:12
Show Gist options
  • Save abel-masila/934df82bd087e7019edcf9f15e4d5634 to your computer and use it in GitHub Desktop.
Save abel-masila/934df82bd087e7019edcf9f15e4d5634 to your computer and use it in GitHub Desktop.
ProductsApp Simple ASP.NET/C#API2
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Product App</title>
<script src="Js/jquery.js"></script>
</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"></p>
<script type="text/javascript">
var uri = "api/product";
$(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 of item to product
$('<li>', { text: formatItem(item) }).appendTo('#products');
});
});
});
function formatItem(item) {
return item.Name + ': Ksh ' + item.Price;
}
function find() {
var id = $("#prodId").val();
$.getJSON(uri + '/' + id)
.done(function (data) {
//On success
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}
</script>
</div>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProductsApp.Models
{
public class Product
{
//The Model
public int Id { get; set; }
public String Name {get; set; }
public String Category { get; set; }
public decimal Price { get; set; }
}
}
using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ProductsApp.Controllers
{
public class ProductController : ApiController
{
Product[] products=new Product[]{
new Product{Id=1,Name="Tomatoes",Category="Groceries",Price=10},
new Product{Id=2,Name="Yo-yo",Category="Toys",Price=75},
new Product{Id=3,Name="Hammer",Category="Hardware",Price=300.50M}
};
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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment