Complete Guide to CRUD operation using $http In Angularjs

In application development, Create, Read, Update, and Delete (CRUD) are the four basic functions of persistent storage, such as databases. CRUD refers to the commonly used functions in the relational database. The following table shows you how CRUD maps to the standard SQL and HTTP:

OperationSQLHTTP
CreateInsertPUT/POST
ReadSelectGET
UpdateUpdatePUT/PATCH
DeleteDeleteDelete

In the following example, we will use $http of the angularjs framework to consume the ASP.NET Web API. In order to call the ASP.NET Web API, we first create a controller in a web API named CustomerController, which has the following action methods:

public class CustomerController : ApiController
    {
        NorthwindEntities _db = new NorthwindEntities();

        
        [HttpGet]
        public IHttpActionResult Customer()
        {
            _db.Configuration.ProxyCreationEnabled = false;

            var customer = _db.Customers;

            if (customer == null)
            {
                return NotFound();
            }
            return Ok(customer);
        }

        
        [HttpGet]
        public IHttpActionResult Customer(string customerID)
        {
            _db.Configuration.ProxyCreationEnabled = false;

            var customer = _db.Customers.FirstOrDefault(c => c.CustomerID == customerID);

            if (customer == null)
            {
                return NotFound();
            }
            return Ok(customer);
        }

        
        [HttpPut]
        public void Customer(Customer data, string customerID)
        {

            if (data.CustomerID == customerID)
            {
                _db.Entry(data).State = EntityState.Modified;
                _db.SaveChanges();
            }

        }

        

        [HttpDelete]
        public void Customer(string customerID, string nothing = null)
        {
            Customer customer = _db.Customers.Find(customerID);

            if (customer != null)
            {
                _db.Customers.Remove(customer);
                _db.SaveChanges();
            }
        }

        
        [HttpPost]
        public void Customer(Customer customer)
        {
            _db.Customers.Add(customer);
            _db.SaveChanges();

        }

    }

 

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares