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.

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

{

publicclass 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);

//added for get

List<Employee> allEmp = new List<Employee>();

using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())

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.