Introduction
WEB API is the best fit to create a resource-oriented service using HTTP/Restful and it works well with MVC-based applications. For more details visit my link.
Description
In this session, I will show you how to insert records using Asp.net Web API or post data to SQL Server. In this session, you can see get and post operations by Web API. In another way, I can say we'll insert and retrieve records using button click event.
Before going through this session, visit my previous session.
Source Code
Steps to be followed.
Step 1
Apply validation on Model.
Go to Solution Explorer > Entities (Project name) > Satyadatabasemodel.tt> Open Employee.cs.
Code Ref
-
-
-
-
-
-
-
-
-
- namespace Entities
- {
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
-
- public partial class Employee
- {
- public int EmployeeID { get; set; }
- [Required(ErrorMessage = "First name required", AllowEmptyStrings = false)]
- public string FirstName { get; set; }
- [Required(ErrorMessage = "Last name required", AllowEmptyStrings = false)]
- public string LastName { get; set; }
- [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
- ErrorMessage = "E-mail is not valid")]
- public string EmailID { get; set; }
- public string City { get; set; }
- public string Country { get; set; }
- }
- }
Code Description
Here, I have applied validation on firstname, lastname, and email field. If the first name and last name will be empty, then the validation message will be displayed. For email field, if the user will input invalid mail address with incorrect domain address, then the email validation message will be shown to the end user.
Step 2
Add a new Action to the SatyaController of SatyaWebApi Web API project for Post Data.
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using Entities;
-
- namespace SatyaWebApi.Controllers
- {
- public class SatyaController : ApiController
- {
-
- public HttpResponseMessage Get()
- {
- List<Employee> allEmp = new List<Employee>();
- using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
- {
- allEmp = dc.Employees.OrderBy(a => a.FirstName).ToList();
- HttpResponseMessage response;
- response = Request.CreateResponse(HttpStatusCode.OK, allEmp);
- return response;
- }
- }
- public HttpResponseMessage Post(Employee emp)
- {
- HttpResponseMessage response;
- if (ModelState.IsValid)
- {
- using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
- {
- dc.Employees.Add(emp);
- dc.SaveChanges();
- }
- response = Request.CreateResponse(HttpStatusCode.Created, emp);
-
-
-
- List<Employee> allEmp = new List<Employee>();
- using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
- {
- allEmp = dc.Employees.OrderBy(a => a.FirstName).ToList();
- HttpResponseMessage response1;
- response1 = Request.CreateResponse(HttpStatusCode.OK, allEmp);
- return response1;
- }
- }
-
- else
- {
- response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error! Please try again with valid data.");
- }
- return response;
- }
- }
- }
Code Description
In this code, I have added post controller action method to perform post data as well as added code about retrieving data inside post action method. The below code is for retrieving the data.
-
-
- List<Employee> allEmp = new List<Employee>();
- using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
- {
- allEmp = dc.Employees.OrderBy(a => a.FirstName).ToList();
- HttpResponseMessage response1;
- response1 = Request.CreateResponse(HttpStatusCode.OK, allEmp);
- return response1;
- }
Code to insert data,
- HttpResponseMessage response;
- if (ModelState.IsValid)
- {
- using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())
- {
- dc.Employees.Add(emp);
- dc.SaveChanges();
- }
- response = Request.CreateResponse(HttpStatusCode.Created, emp);
- dc.Employees.Add(emp);
- dc.SaveChanges();
Here, using datacontext object adds data and passes to the emp parameter in post action method and saves all changes made in this to the underlying database.
- else
- {
- response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error! Please try again with valid data.");
- }
If any connection issue will be found or any related issue in code or invalid data during post operation then the error message will be shown to the end user.
Step 3
Add a new Action to the HomeController in SatyaConsumingApi for getting view to Post data.
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Web;
- using System.Web.Mvc;
- using Entities;
-
- namespace SatyaConsumingApi.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Part1()
- {
- return View();
- }
-
- public ActionResult Part2()
- {
- List<Employee> list = new List<Employee>();
- HttpClient client = new HttpClient();
- var result = client.GetAsync("http://localhost:47250/api/satya").Result;
- if (result.IsSuccessStatusCode)
- {
- list = result.Content.ReadAsAsync<List<Employee>>().Result;
- }
- return View(list);
- }
- public ActionResult Part3()
- {
- return View();
- }
-
- }
- }
Code Description
Here Part 3 is the new controller action mentiod in MVC client application.
Step 4
Add view for the Action.
Code Ref
- @{
- ViewBag.Title = "Satyaprakash - Post Data To Web API Using jQuery With Validation";
- }
-
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
-
-
- <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">
-
- </script>
-
- <style>
- .error, #error {
- color: red;
- display: none;
- }
-
- table {
- font-family: arial, sans-serif;
- border-collapse: collapse;
- width: 100%;
- }
-
- td, th {
- border: 1px solid #dddddd;
- text-align: left;
- padding: 8px;
- }
-
- tr:nth-child(even) {
- background-color: #dddddd;
- }
-
- .button {
- background-color: #4CAF50;
- border: none;
- color: white;
- padding: 15px 32px;
- text-align: center;
- text-decoration: none;
- display: inline-block;
- font-size: 16px;
- margin: 4px 2px;
- cursor: pointer;
- }
-
- .button4 {
- border-radius: 9px;
- }
- </style>
-
- <div style="padding:10px ; align-content:center">
- <fieldset>
- <legend style="font-family:Arial Black;color:blue">Post Data To Web API Using jQuery With Validation</legend>
- </fieldset>
- </div>
-
- <div class="container1">
- <form id="frm1" role="form" style="max-width:500px">
- <div class="form-group">
- <div id="error"> </div>
- </div>
- <div class="form-group">
- <label for="firstname" style="color:blue">First Name:</label>
- <input type="text" class="form-control" id="firstname" placeholder="please enter First Name">
- <span class="error">Please provide First Name</span>
- </div>
- <div class="form-group">
- <label for="lastname" style="color:blue">Last Name:</label>
- <input type="text" class="form-control" id="lastname" placeholder="please enter Last Name">
- <span class="error">Please provide Last Name</span>
- </div>
- <div class="form-group">
- <label for="email" style="color:blue">Email:</label>
- <input type="text" class="form-control" id="email" placeholder="please enter Email-Id">
- <span class="error">Invalid email ID</span>
- </div>
- <div class="form-group">
- <label for="city" style="color:blue">City:</label>
- <input type="text" class="form-control" id="city" placeholder="please enter City">
- </div>
- <div class="form-group">
- <label for="country" style="color:blue">Country:</label>
- <input type="text" class="form-control" id="country" placeholder="please enter Country">
- </div>
- <button type="submit" class="button button4">Submit</button>
- </form>
- </div>
-
- <div id="updatePanel" style="width:90%; margin:0 auto; padding:10px">
-
- </div>
-
- @section Scripts{
- <script>
- $(document).ready(function () {
- var apiBaseUrl = "http://localhost:47250/";
- $('#frm1').submit(function (e) {
- e.preventDefault();
- var isOK = ValidateForm();
- if (isOK) {
- var emp = {
- EmployeeID: 0,
- FirstName: $('#firstname').val().trim(),
- LastName: $('#lastname').val().trim(),
- EmailID: $('#email').val().trim(),
- City: $('#city').val().trim(),
- Country: $('#country').val().trim()
- };
-
-
- $.ajax({
- url: apiBaseUrl+'api/satya',
- type: 'POST',
- dataType: 'json',
- data: emp,
- success: function (d) {
- bootbox.alert('Data Is Successfully Saved!');
- var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');
- var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">Full Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');
- $table.append($header);
- $.each(d, function (i, val) {
- var $row = $('<tr/>');
- $row.append($('<td/>').html(val.FirstName + ' ' + val.LastName));
- $row.append($('<td/>').html(val.EmailID));
- $row.append($('<td/>').html(val.City));
- $row.append($('<td/>').html(val.Country));
- $table.append($row);
- });
- $('#updatePanel').html($table);
-
- var frm = document.getElementById('frm1');
- frm.reset();
- },
- error: function () {
- $('#error').html('Error! please try with valid data.').show();
- }
- });
- }
- });
- });
- function ValidateForm() {
- var isAllValid = true;
- $('.error').hide();
- $('#error').empty();
- $('.form-group').removeClass('has-error');
- if ($('#firstname').val().trim()=="") {
- $('#firstname').focus();
- $('#firstname').siblings('.error').show();
- $('#firstname').parents('.form-group').addClass('has-error');
- isAllValid = false;
- }
- if ($('#lastname').val().trim() == "") {
- $('#lastname').focus();
- $('#lastname').siblings('.error').show();
- $('#lastname').parents('.form-group').addClass('has-error');
- isAllValid = false;
- }
- if ($('#email').val().trim() != "") {
-
- var expr = /^([a-zA-Z0-9_\-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
- if (!expr.test($('#email').val().trim())) {
- $('#email').focus();
- $('#email').siblings('.error').show();
- $('#email').parents('.form-group').addClass('has-error');
- isAllValid = false;
- }
- }
- return isAllValid;
- }
- </script>
- }
Code Description
I created a script function to validate form control named "ValidateForm()" . If successfully validated then post data operation will be performed and then it will retrieve the data after successful post operation. Then all input fields will be reset else the error message will be shown due to invalid data.
- $.ajax({
- url: apiBaseUrl+'api/satya',
- type: 'POST',
- dataType: 'json',
- data: emp,
- success: function (d) {
- bootbox.alert('Data Is Successfully Saved!');
- var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');
- var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">Full Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');
- $table.append($header);
- $.each(d, function (i, val) {
- var $row = $('<tr/>');
- $row.append($('<td/>').html(val.FirstName + ' ' + val.LastName));
- $row.append($('<td/>').html(val.EmailID));
- $row.append($('<td/>').html(val.City));
- $row.append($('<td/>').html(val.Country));
- $table.append($row);
- });
- $('#updatePanel').html($table);
-
- var frm = document.getElementById('frm1');
- frm.reset();
- },
- error: function () {
- $('#error').html('Error! please try with valid data.').show();
- }
- });
The CDN reference should be added for bootbox alert message support.
- bootbox.alert('Data Is Successfully Saved!');
- <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js">
-
- </script>
Step 5
Add bootstrap css for a good appearnace in _Layout.cshtml.
- @* @Styles.Render("~/Content/css")*@
- @* Add bootstrap css for good looks *@
- <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
- @Scripts.Render("~/bundles/modernizr")
OUTPUT
The Part 3 view will look as shown below..
For First and Last Name Validations....
For Email field validation..
For a successful alert message post data using bootbox javascript library.
After successful post data get data or bind data into table.
Check Database for record insert operation.
Responsive web page for tablets and mobile phones.
Gif image for better understanding.
SUMMARY
- Post and Get operation using one controller action method in Asp.Net Web API.
- Post data with form control validation.
- Bootbox javascript library for alert message.
- Mobile responsive support.