Saturday, July 25, 2015

AngularJS $http.post Ajax calls

In the post AngularJS Ajax using $http we saw that we can perform Ajax calls to the server in AngularJS using $http service, and we saw that $http supports Get, Post, Put and Delete operations. In this post we shall see on how to make a $http.post Ajax call in AngularJS

The following example shows how to make a $http.post call to an Asp.Net Web API Controller method.
WebAPI Post Method
    public class PackageController : ApiController
    {
        PkgEntities objDBContext = new PkgEntities();
        //
        [HttpPost]
        public string Post(Package objPackage)
        {
            try
            {
                objDBContext.Packages.Add(objPackage);
                objDBContext.SaveChanges();
                return "Package " + objPackage.Name + " added Succesfully";
            }
            catch (Exception ex)
            {
                return "Error: " + ex.Message.ToString();
            }
 }
}
AngularJS call to WebAPI Get method
    this.AddPackage = function (scope) {
        var dataObj = {
            Name: scope.Name,
            Description: scope.Description,
            PackageSQL: scope.PackageSQL,
            Status: scope.Status
        };
        //
        $http.post(GetRootPath() + "Package", dataObj)
           .then(function (results) {
               //Success;
               try {
                   alert(results.data);
               }
               catch (err) {
                   alert(err.message);
               }
           }, function (results) {
               //error
               alert("Error: " + results.data + "; "
                                     + results.status);
           })

    }

The $http.post method creates a JSON object objData calls the server side WebAPI Post() method and passes the object as parameter to the WebAPI method. The WebAPI contoroller method receives the package object from the $http.post call and inserts a new package to the database context and returns a success/failure message to AngularJS. The AngularJS client method receives the message and displays it to the end user.

Search Flipkart Products:
Flipkart.com

No comments: