Introduction
In this article, I am going to explain how we post (put) data to Web API.
Code: Let's see the code and understand what we need to implement here.
Step 1: First all we will see what are POST and PUT methods in the Customer Controller.
In the following code, the Post Method will take a CustomerModel.
- // POST /api/customer
- public void Post(CustomerModel customer)
- {
- context.AddToCustomers(new Customer { Id = customer.Id, Name = customer.Name, Salary = customer.Salary });
- context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
- }
In the following code, the Put Method will take CustomerModel and customerID.
- // PUT /api/customer/5
- public void Put(int id, CustomerModel customer)
- {
- var cust = context.Customers.First(c => c.Id == id);
- cust.Name = customer.Name;
- cust.Salary = customer.Salary;
- context.SaveChanges();
- }
Now in Step 2 will see how we can post data to a Web API using JSON.
Step 2: See the highlighted code inside the JQuery block. We have created an instance of a CustomerModel Object inside a JavaScript block:
- <script type="text/javascript">
- $(document).ready(function(){
- var CustomerCreate = {
- Name: "Jackson",
- Salary: 22222
- };
- createCustomer(CustomerCreate, function (newCustomer) {
- alert("New Customer created with an Id of " + newCustomer.Id);
- });
- $("#AddCustomer").click(function () {
- createCustomer(CustomerCreate, null);
- });
- function createCustomer(CustomerCreate, callback) {
- $.ajax({
- url: "/api/Customer",
- data: JSON.stringify(CustomerCreate),
- type: "POST",
- contentType: "application/json;charset=utf-8",
- statusCode: {
- 201: function (newCustomer) {
- callback(newCustomer);
- }
- }
- });
- }});
- </script>


Join the conversation! Your thoughts help the community grow.