Welcome to the next part of a tutorial in the WebAPI series. In this post, I am going to explain, how to post and save the user entered data in the database, using Web API service. If you are new to Web API in ASP.NET MVC5, please refer to the posts given below for the basics of WebAPI.
- Introduction to WebAPI.
- How to fetch and display data from WebAPI in ASP.NET MVC5
Now, let's begin our tutorial:
Create Visual studio application
- Create a ASP.NET Web Application(Visual Studio 2013 or 2015), using Empty MVC template.
- It is a great idea to start any Application, using an empty template because there is more scope for learning and implementing every thing from scratch (not for production).
- Now, our solution contains basic MVC project structure.
- Add a database to the App_Data folder (by right click App_Data folder --> Add --> New Item --> Select SQL database, under Data section --> name it --> Add.
- Create a table in the database with the code, given below:
- 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
- Right click on Models folder--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from the database (In Entity Data Model wizard) --> Next.
- Select the database --> give name for web.config.
- Choose your database objects(tables) and click finish.
- Now, Model is added to my project.
Note: Now, we have to create a WebAPI controller. For it, this article will help you to setup WebAPI in your Application Introduction to WebAPI in ASP.NET MVC 5.
Web api controller to Application
- Replace the code of WebAPI controller with the code, given below:
- 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
- Here, client is a simple View page (Index .cshtml page from PostController).
- Create a Controller by right clicking on Controllers folder --> name it as a PostController.
- I created an Index action method and added a view with Index.cshtml name.
-
- public ActionResult Index()
- {
- return View();
- }
- In this View, I added a simple jQuery AJAX method to post the data to Web API Service.
- Replace the Index view code with the code, given below:
- @{
- 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 have not implemented client side validation.
- Here, I am reading the form values, using jQuery.and posting form values to Web API for saving on the database.
- The output of the Application is:
- After saving the data on the Server, you will get a message like:
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, subscrib to it. See this tutorial in my blog.