Access service methods of WCF.Net by using ajax

Step 1: Create Model
public class CustomerDetail
    {
        [Key]
        public int RowId { get; set; }
        [Required]
        public string FisrtName { get; set; }
        public string LastName { get; set; }
        public string FatherName { get; set; }
        public DateTime DOB { get; set; }
        public string Gender { get; set; }
        public string Education { get; set; }
    }
Step 2: Create Context class for Customer
public partial class CustomerDbAccess : DbContext
    {
        public CustomerDbAccess() : base("name=defaultConnection")
        {

        }
         
        public virtual DbSet CustomerDetails { get; set; } 
    }
Step 3: CustomerBusinessLayer class
public class CustomerBusinessLayer 
    { 
        public List GetCustomers()
        {
            List lst = (List)null;
            using (var db = new CustomerDbAccess())
            {
                lst = db.CustomerDetails.ToList();
            }
            return lst;
        }

        public string SaveCustomers(CustomerDetail cust)
        {
            
            using (var db = new CustomerDbAccess())
            {
                if (cust.RowId < 1) // Insert
                {
                    db.CustomerDetails.Add(cust);
                }
                else  // Update
                {
                    db.Entry(cust).State = System.Data.Entity.EntityState.Modified;
                }
                db.SaveChanges();
            }
            return "Record is saved"
        }

        public string DeleteCustomers(int id)
        {
            try
            {
                if (id < 1) return "Invalid Id";
                CustomerDetail custToDelete;
                using (var ctx = new CustomerDbAccess())
                {
                    custToDelete = ctx.CustomerDetails.Where(s => s.RowId == id).FirstOrDefault();
                    if (custToDelete == null) return "Invalid Id";
                   ctx.Entry(custToDelete).State = System.Data.Entity.EntityState.Deleted;
                    ctx.SaveChanges();
                }
                return "Record is deleted";
            }
            catch(Exception ex)
            {
                return "Error:" + ex.Message;
            }
        }
}
Step4: Create service methods for Insert, Update and Delete
// Service Interface
 [ServiceContract]
    public interface ICustomer
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        string GetDetails();

        [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        string SaveDetails(CustomerDetail cust);

        [OperationContract]
        [WebInvoke(Method = "DELETE", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/CustomerDelete/{deleteRowId}")]
        string DeleteDetails(string deleteRowId);
    }

// Service Class
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Customer : ICustomer
{
        CustomerBusinessLayer db;
        public Customer()
        {
            db = new CustomerBusinessLayer();
        }

        public string GetDetails()
        {            
            List cust = db.GetCustomers();
            return (new JavaScriptSerializer().Serialize(cust));
        }

        public string SaveDetails(CustomerDetail cust)
        {
            return db.SaveCustomers(cust);
        }

        public string DeleteDetails(string deleteRowId)
        {
            int rowID = Convert.ToInt32(deleteRowId);
            return db.DeleteCustomers(rowID);
        }

    }
Step 5 : Set service endpoint and behaviors in web.config

<system.serviceModel>
<services>
<service name="TestWCFApp.Services.Customer" behaviorConfiguration="serviceBasicBehavior">
<endpoint behaviorConfiguration="ServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="TestWCFApp.Services.ICustomer" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="ServiceAspNetAjaxBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="serviceBasicBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>

Step 6: Enable CORS in WCF application
// Add in global.asax file
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Code for HTML File

<script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function fillRecords() {
$('#tableGrid tbody tr').remove();
$.ajax({
type: "Get",
contentType: "application/json; charset=utf-8",
url: 'http://localhost:50909/Services/Customer.svc/GetDetails',
dataType: "json",
success: function (response) {
var customers = $.parseJSON(response);
if (customers != null && customers.length > 0) {
var html = "";
$.each(customers, function (i, item) {
var f = new Date(item.DOB.match(/\d+/)[0] * 1);
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var DOB = f.getDate() + "-" + months[f.getMonth()] + "-" + f.getFullYear();
var id = item.RowId;

html += "<tr>";
html += "<td id='FisrtName_" + id + "'>" + item.FisrtName + "</td>";
html += "<td id='LastName_" + id + "'>" + item.LastName + "</td>";
html += "<td id='FatherName_" + id + "'>" + item.FatherName + "</td>";
html += "<td id='DOB_" + id + "'>" + DOB + "</td>";
html += "<td id='Gender_" + id + "'>" + item.Gender + "</td>";
html += "<td id='Education_" + id + "'>" + item.Education + "</td>";
html += "<td class='editRecord' onclick=editRecord(" + id + ") style='cursor:pointer'>Edit</td>";
html += "<td class='deleteRecord' onclick=deleteRecord(" + id + ") style='cursor:pointer'>Delete</td>";
html += "</tr>";
});
$('#tableGrid tbody').append(html);
// $(html).appendTo($("#tableGrid"));
}

},
error: function (a, b, c) {
alert(a.responseText);
}
});
}
$(document).ready(function () {
$("#ClearData").click(function () {
alert('cancelRecord');
cancelRecord();
});

$("#SaveData").click(function () {
var rowId = parseInt($("#RowId").val());
var fName = $("#FisrtName").val();
var lName = $("#LastName").val();
var faName = $("#FatherName").val();
var doo = new Date($("#DOB").val());
var gender = $("#Gender").val();
var education = $("#Education").val();
var birthDate = '/Date(' + (doo.getTime() + Math.abs(doo.getTimezoneOffset() * 60000)) + ')/';
if (rowId == null || isNaN(rowId)) { rowId = 0; }
var cust = { RowId: rowId, FisrtName: fName, LastName: lName, FatherName: faName, DOB : birthDate, Gender: gender, Education: education };
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: 'http://localhost:50909/Services/Customer.svc/SaveDetails',
data: JSON.stringify(cust),
dataType: "json",
success: function (response) {
alert(response);
fillRecords();
cancelRecord();
},
error: function (a, b, c) {
alert(a.responseText);
}
});
});

fillRecords();
});

function editRecord(rowid) {
var fName = $("#FisrtName_" + rowid).html();
var lName = $("#LastName_" + rowid).html();
var faName = $("#FatherName_" + rowid).html();
var dob = $("#DOB_" + rowid).html();
var gender = $("#Gender_" + rowid).html();
var education = $("#Education_" + rowid).html();

$("#RowId").val(rowid);
$("#FisrtName").val(fName);
$("#LastName").val(lName);
$("#FatherName").val(faName);
$("#DOB").val(dob);
$("#Gender").val(gender);
$("#Education").val(education);
}

function deleteRecord(rowid) {
$.ajax({
type: "DELETE",
contentType: "application/json; charset=utf-8",
url: 'http://localhost:50909/Services/Customer.svc/CustomerDelete/' + rowid,
dataType: "json",
success: function (response) {
alert(response);
fillRecords();
cancelRecord();
},
error: function (a, b, c) {
alert(a.responseText);
}
});
fillRecords();
cancelRecord();
}

function cancelRecord() {
$("#RowId").val();
$("#FisrtName").val();
$("#LastName").val();
$("#FatherName").val();
$("#DOB").val();
$("#Gender").val();
$("#Education").val();
}
</script>
<div class="jumbotron">
<h1>Test</h1>
</div>
<div>
<table id="tableGrid">
<thead>
<tr>
<td>Fisrt Name</td>
<td>Last Name</td>
<td>Father Name</td>
<td>DOB</td>
<td>Gender</td>
<td>Education</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="row">
<div>
Fisrt Name: <input type="text" id="FisrtName" /><br/>
Last Name: <input type="text" id="LastName" /><br/>
Father Name: <input type="text" id="FatherName" /><br/>
DOB: <input type="text" id="DOB" /><br/>
Gender: <input type="text" id="Gender" /><br/>
Education: <input type="text" id="Education" /><br/>
<br/>
<input type="hidden" id="RowId" />
<input id="SaveData" type = "button" value = "Save" />
<input id="ClearData" type = "button" value = "Clear" />
</div>
</div>