Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Wednesday, April 20, 2016

Mustache JS Ajax call

Earlier we saw how we can use MustachJs to display the hardcoded data in the browser.
Now lets call our MVC controller thru ajax  and get the data and then display it on browser


For this additional we got to add Jquery CDN for ajax calls


<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>


Below is the script to make an ajax "Get" call to the controller and display the data



<script>

        var template,  html;

     

        $.getJSON('http://localhost:52456/api/RiskDetailApi', function (data) {

            debugger

            template = "<h2>RiskDecription: {{RiskDecription}} </h2>";

           

            html = Mustache.render(template, data[0]);

            document.write(html);

        });

     

      

      

    </script>




$.getJSON converts the data to Json format
Run the solution and BOOOM!!! you see the dynamic data on the browser


Tuesday, March 1, 2016

Angular JS with WebApi-Get

Earlier we saw how to make ajax calls from JQuery to consume WebApi Services .
the Same is shown here with angular js as a JavaScript framework .

Create a webApi controller and its method to get the data  from Database

public class EmployeeController : ApiController

    {

        private DRMSEntities1 db = new DRMSEntities1();

 

        // GET api/Employee

        public IQueryable<DRMS_Tbl_Employee> GetDRMS_Tbl_Employee()

        {

            return db.DRMS_Tbl_Employee;

        }
}

Create an HTML page to make ajax calls and display the result on the browser

View

 

<!DOCTYPE html>

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

<head>

 
//CDN//
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.js"></script>

    <script src="Scripts/bootstrap.js"></script>

    <link href="Content/bootstrap.css" rel="stylesheet" />

    <title></title>

</head>

<body ng-app="RiskModule">

    <h1>hi {{2+2}}</h1>

    <div ng-controller="RiskDetailsController">

        {{Employee.EmployeeName}}

//binding Json result to table

        <table ng-repeat="Emp in Employee"  class="table table-condensed">

            <tr>

                <td>

                    {{Emp.EmployeeID}}

                </td>

                <td>{{Emp.EmployeeName}}</td>

                <td>{{Emp.Email}}</td>

                <td>{{Emp.RoleId}}</td>

            </tr>

        </table>

        <script >
//Making Ajax calls

            var app = angular.module("RiskModule", []);

            app.controller("RiskDetailsController", function ($scope, $http) {

                $http.get('http://localhost:60228/api/Employee').

                success(function (data, status, header, config) {

                    $scope.Employee = data;

                }).

                error(function (data, status, header, config) {

                    alert("Error");

                });

 

            });

        </script>

    </div>

 

</body>

 

 

</html>
Run the solution and you will see the result as below


 

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;






}


}