Post Data to MVC 4 WEB API .NET 4.5

Introduction

In the previous Article http://www.c-sharpcorner.com/UploadFile/amit12345/mvc-4-web-api-net-4-5/ we saw how to get data from a Web API in various formats.

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>

In the HTML body we have added one HTML anchor tag and above inside the JavaScript block we have registered a click event for the anchor tag. Now when the user clicks on the anchor link, data will be posted to the server.

 <body>
    <header>
        <div class="content-wrapper">
            <div class="float-left">
                <p class="site-title"><a href="/">ASP.NET Web API</a></p>
            </div>
        </div>
    </header>
    <div id="body">
        <a id="AddCustomer" href="#">Create New Customer</a>
    </div>
</
body>

In the following image we can see how the data will be sent via the Post Method:

PostwepApi2.png

 Happy Coding.

Up Next
    Ebook Download
    View all
    Learn
    View all