How to post data to webapi using Jquery in ASP.NET MVC5

Datetime:2016-08-22 22:05:51          Topic: jQuery  ASP.NET           Share

Welcome to next part of tutorial in wepapi series.In this post i am going to explain about How to post and save the user entered data in database using web api service. If you are new to web api in ASP.NET MVC5 please refer the below posts for basics of WEBAPI.

Introduction to WEBAPI

How to fetch and display data from webapi in ASP.NET MVC5

Now lets begin our tutorial..

Create Visual studio application

1.Create a ASP.NET Web application(visual studio 2013 or 2015) using Empty MVC template.

2.It is a great idea to start any application using Empty template because there is more scope for learning and implementing every thing from scratch(not for production).

3.Now our solution contains basic MVC project structure.

4.Add a Database to the App_Data folder (by right click App_Data folder --> Add --> New Item --> Select Sql Data base under Data section --> name it --> Add.

5.Create a table in data base with below code.

CREATE TABLE [dbo].[Student] (
    [StudentID]   INT          NOT NULL,
    [StudentName] VARCHAR (50) NOT NULL,
    [Email]       VARCHAR (50) NOT NULL,
    [City]        VARCHAR (50) NULL,
    [Contact]     BIGINT       NULL,
    [Country]     VARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([StudentID] ASC)
);

Add ADO.NET Entity Data Model

1.Right click on Models folder--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next

2.Select Database --> give name for web.config.

3.Choose your Database objects(tables) and click finish.

4.Now Model is added to my project.

Note: Now we have to create a Webapi controller for that this article will help you to setup webapi in your application Introduction to WebAPI in ASP.NET MVC 5

Web api controller to Application

1.Replace the code of webapi controller with below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using PostingDatainWebAPI.Models;

namespace PostingDatainWebAPI.Controllers
{
   public class StudentAPIController : ApiController
    {
        public HttpResponseMessage Post(Student student)
        {
            HttpResponseMessage result;
            if (ModelState.IsValid)
            {
                using (StudentDataBaseEntities db = new StudentDataBaseEntities())
                {
                    db.Students.Add(student);
                    db.SaveChanges();                   
                }
                result = Request.CreateResponse(HttpStatusCode.Created, student);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest, "Server failed to save data");
            }
             return result;
        }
    }
}

Create a User form page to input some data

1.Here client is simple View page(Index .cshtml page from PostController) .

2.Create a Controller by right clicking on Controllers folder --> i named it as PostController .

3.I created Index action method and added view with Index.cshtml name.

//Using Jquery
        public ActionResult Index()
        {
            return View();
        }

4.In this View i added a simple jquery ajax method to post data to web api service.

5.Replace the Index view code with below code.

@{
    ViewBag.Title = "Posting Data to WEBAPI using Jquery";
}

<h3 class="text-info">Posting Data to WEBAPI using Jquery</h3>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<style>
    input{
        max-width:250px;
    }
</style>
<h5 class="text-danger"><b>Note:</b>Please Enter all details correctly and submit
    Here i did not applied validations to this form</h5>
 <div class="container">
     <form name="postform" id="postform" class="form-horizontal">
            <div class="form-group">
                <label class="text-info">Student ID</label>
                <input type="number" id="txtStudentID" class="form-control" />
            </div>
            <div class="form-group">
                <label class="text-info">Student Name</label>
                <input type="text" id="txtStudentName" class="form-control" />
            </div>
            <div class="form-group">
                <label class="text-info">Email</label>
                <input type="email" id="txtEmail" class="form-control" />
            </div>
            <div class="form-group">
                <label class="text-info">City</label>
                <input type="text" id="txtCity" class="form-control" />
            </div>
            <div class="form-group">
                <label class="text-info">Contact Number</label>
                <input type="number" id="txtContact" class="form-control" />
            </div>
            <div class="form-group">
                <label class="text-info">Country</label>
                <input type="text" id="txtCountry" class="form-control" />
            </div>

            <button type="submit" class="btn btn-default">Save</button>
     </form>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $("#postform").submit(function (e) {
            e.preventDefault();
            var apiurl = "http://localhost:9627/api/StudentAPI";
            var data = {
                StudentID: $("#txtStudentID").val().trim(),
                StudentName: $("#txtStudentName").val().trim(),
                Email: $("#txtEmail").val().trim(),
                City: $("#txtCity").val().trim(),
                Contact: $("#txtContact").val().trim(),
                Country: $("#txtCountry").val().trim(),
            }
            $.ajax({
                url: apiurl,
                type: 'POST',
                dataType: 'json',
                data: data,
                success: function (d) {
                    alert("Saved Successfully");
                    document.getElementById("postform").reset();
                },
                error: function () {
                    alert("Error please try again");
                }
            });
        });
    });

</script>

Note: For this form i did not implemented client side validation.

6.Here simply i am reading the form values usingjquery.and posting form values to web api for saving on database.

7.the output of the application is..

8.After saving data on server you will get a message like this..

Download the source code of this application here.. Source Code (Visual studio 2015 code)

Conclusion

I hope this tutorial is understandable and useful for every reader.If you are not subscribed to this blog  subscribe .follow on Social networks for daily awesome updates[F acebook , twitter , google plus] .





About List