Wednesday, January 6, 2016

Consuming WebApi Services

consuming WebApi can be made simple by Using Jquery Ajax
View side Jquery Ajax code is below :







@{


ViewBag.Title = "MyBooks";






}


 
<h2>MyBooks</h2>

<button id="btnGetBooks">Get Books</button>


<div id="div1"></div>





@section Scripts{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>


<script type="text/javascript">


$(document).ready(function () {

$('#btnGetBooks').on("click", function () {






$.ajax(


{
type: "GET",

url: '/api/BooksApi',

dataType:"json",

async: true,

//ProcessData: false,


//cache:false,

                    success: function (data) {

//console.log(data);


$('#div1').html(JSON.stringify(data));



alert(data);
alert('success');


},
error: function (xhr) {

 
}


});


});


});
 
</script>


}

=========================================================================================
 



Model Class
public class Books





{


public int id { get; set; }

public string Name { get; set; }






}




Context class
public class BooksContext : DbContext





{





public BooksContext() : base("name=BooksContext")






{


}


public System.Data.Entity.DbSet<Webapi1.Models.Books> Books { get; set; }









}

===================================================================================

API code



Create an api controller for Books class




public class BooksApiController : ApiController





{


private BooksContext db = new BooksContext();









// GET api/BooksApi


public IQueryable<Books> GetBooks()






{


return db.Books;






}


// GET api/BooksApi/5


[ResponseType(typeof(Books))]

public IHttpActionResult GetBooks(int id)






{


Books books = db.Books.Find(id);

if (books == null)






{


return NotFound();






}


return Ok(books);






}


// PUT api/BooksApi/5


public IHttpActionResult PutBooks(int id, Books books)






{


if (!ModelState.IsValid)






{


return BadRequest(ModelState);






}


if (id != books.id)






{


return BadRequest();






}


db.Entry(books).State = EntityState.Modified;

try





{


db.SaveChanges();


}


catch (DbUpdateConcurrencyException)






{


if (!BooksExists(id))






{


return NotFound();






}


else





{


throw;






}


}


return StatusCode(HttpStatusCode.NoContent);






}


// POST api/BooksApi


[ResponseType(typeof(Books))]

public IHttpActionResult PostBooks(Books books)






{


if (!ModelState.IsValid)






{


return BadRequest(ModelState);






}


db.Books.Add(books);


db.SaveChanges();


return CreatedAtRoute("DefaultApi", new { id = books.id }, books);






}


// DELETE api/BooksApi/5


[ResponseType(typeof(Books))]

public IHttpActionResult DeleteBooks(int id)






{


Books books = db.Books.Find(id);

if (books == null)






{


return NotFound();






}


db.Books.Remove(books);


db.SaveChanges();


return Ok(books);






}


protected override void Dispose(bool disposing)






{


if (disposing)






{


db.Dispose();


}


base.Dispose(disposing);






}


private bool BooksExists(int id)






{


return db.Books.Count(e => e.id == id) > 0;






}


}







 


 



No comments:

Post a Comment