Skip to content

ADD, EDIT, DELETE and SEARCH data with Web API Controller, CODE FIRST(EF) through jQuery.

February 17, 2013

1.     Design page’s Code with jQuery validation code

<%@PageTitle=”Student
Page”
Language=”C#”MasterPageFile=”~/Home.Master”AutoEventWireup=”true”CodeBehind=”StudentPage.aspx.cs”Inherits=”FEB.Pages.StudentPage”%>

 

<asp:ContentID=”Content1″ContentPlaceHolderID=”head”runat=”server”>

<style>

.error_group {

background-color: #A52A2A;

color: #00FFFF;

padding: 10px;

display: none;

margin: 5px;

}

</style>

</asp:Content>

 

<asp:ContentID=”Content2″ContentPlaceHolderID=”ContentPlaceHolder1″runat=”server”>

 

<tablestyle=”border: 1pxsolidred;“>

<tr>

<tdcolspan=”2″>

<divclass=’error_group’id=’error_group’>

</div>

</td>

</tr>

<tr>

<td>Name</td>

<td>

<asp:TextBoxrunat=”server”ID=”NameTxt”></asp:TextBox></td>

</tr>

<tr>

<td>Parent</td>

<td>

<asp:TextBoxrunat=”server”ID=”ParentTextBox”></asp:TextBox></td>

</tr>

<tr>

<td>Age</td>

<td>

<asp:TextBoxrunat=”server”ID=”AgeTextBox”></asp:TextBox></td>

</tr>

<tr>

<td></td>

<td>

<buttontype=”submit”id=”byAjaxButton”>Add</button>

</td>

</tr>

<tr>

<td>Search
by id
</td>

<td>

<inputtype=”text”id=”SearchbyID”/>

<buttontype=”submit”id=”idbutton”>Find</button></td>

</tr>

 

<tr>

<tdcolspan=”2″>

<tableid=”gvDetails”border=”1″></table>

</td>

</tr>

</table>

 

 

<scripttype=”text/javascript”>

var
check =
false;

var Sid
=
;

$(‘#byAjaxButton’).click(function (e)
{

e.preventDefault();

var
error = 0;

$(‘#error_group’).html(“”);

var name
= $(
‘#<%=NameTxt.ClientID%>).val();

if
(name ==
) {

error = 1;

$(‘#error_group’).append(“Name
cannot be empty.<br>”
);

}

var
parent = $(
‘#<%=ParentTextBox.ClientID%>).val();

if
(parent ==
) {

error = 1;

$(‘#error_group’).append(“Parent
cannot be empty.<br>”
);

}

var age
= $(
‘#<%=AgeTextBox.ClientID%>).val();

if (age
==
) {

error = 1;

$(‘#error_group’).append(“Age
cannot be empty.<br>”
);

}

 

if
(error) {

$(‘#error_group’).show();

returnfalse;

} else {

$(‘#error_group’).hide();

var data
= JSON.stringify({

Name: $(‘#<%=NameTxt.ClientID%>).val(),

Parent: $(‘#<%=ParentTextBox.ClientID%>).val(),

Age: $(‘#<%=AgeTextBox.ClientID%>).val()

});

if
(!check) {

AddData(data);

} else {

UpdateData(data, Sid);

}

}

 

});

 

function
AddData(data) {

$.ajax({

type: ‘Post’,

url: ‘api/student’,

data: data,

contentType: “application/json;
charset=utf-8”
,

dataType: “json”,

success: function () {

bind();

},

error: function () {

alert(“Erroe”);

}

});

}

function
UpdateData(data, id) {

$.ajax({

type: ‘Put’,

url: ‘api/student/’ +
id,

data: data,

contentType: “application/json;
charset=utf-8”
,

dataType: “json”,

success: function () {

bind();

},

error: function () {

alert(“Erroe”);

}

});

}

function
Edit(id) {

$.ajax({

type: ‘Get’,

url: ‘api/student/’ +
id,

contentType: ‘application/json;
charset=utf-8’
,

dataType: ‘json’,

success: function
(data) {

$(‘#<%=NameTxt.ClientID%>).val(data.Name);

$(‘#<%=ParentTextBox.ClientID%>).val(data.Parent);

$(‘#<%=AgeTextBox.ClientID%>).val(data.Age);

check = true;

Sid = id;

$(‘#byAjaxButton’).text(‘Update’);

},

error: function () {

alert(“Error”);

}

});

}

function
Delete(id) {

var r =
confirm(
“You want to delete!”);

if (r
==
true) {

$.ajax({

type: ‘Delete’,

url: ‘api/student/’ +
id,

contentType: ‘application/json;
charset=utf-8’
,

dataType: ‘json’,

success: function () {

bind();

},

error: function () {

alert(“Error”);

}

});

}

}

function
bind() {

 

$.ajax({

type: ‘Get’,

url: ‘api/student’,

contentType: ‘application/json;
charset=utf-8’
,

dataType: ‘json’,

success: function
(data) {

bindGrid(data);

 

},

error: function () {

alert(“Error”);

}

});

}

 

$(‘#idbutton’).click(function (e)
{

e.preventDefault();

var id =
$(
‘#SearchbyID’).val();

$.ajax({

type: ‘Get’,

url: ‘api/student/’ +
id,

contentType: ‘application/json;
charset=utf-8’
,

dataType: ‘json’,

success: function
(data) {

$(“#gvDetails”).empty();

$(‘#gvDetails’).append(“<tr><th>SN</th>” +

“<th>Name</th>” +

“<th>Parent</th>” +

“<th>Age</th>” +

“<th></th>” +

“<th></th>” +

“</tr>”);

 

$(“#gvDetails”).append(“<tr><td>”

+ data.ID + “</td><td>”

+ data.Name + “</td><td>”

+ data.Parent + “</td><td>”

+ data.Age + “</td><td>”

+ “<a
href=’javascript:void(0)’ onclick=’Edit(“
+ data.ID + “)’>Edit</a></td><td>”

+ “<a
href=’javascript:void(0)’ onclick=’Delete(“
+ data.ID + “)’>Delete</a>” +

“</td></tr>”);

 

},

error: function () {

alert(“Error”);

}

});

});

function
bindGrid(data) {

if
(data.length != 0) {

$(“#gvDetails”).empty();

$(‘#gvDetails’).append(“<tr><th>SN</th>” +

“<th>Name</th>” +

“<th>Parent</th>” +

“<th>Age</th>” +

“<th></th>” +

“<th></th>” +

“</tr>”);

$.each(data, function
(key, val) {

$(“#gvDetails”).append(“<tr><td>”

+ val.ID + “</td><td>”

+ val.Name + “</td><td>”

+ val.Parent + “</td><td>”

+ val.Age + “</td><td>”

+ “<a
href=’javascript:void(0)’ onclick=’Edit(“
+ val.ID + “)’>Edit</a></td><td>”

+ “<a
href=’javascript:void(0)’ onclick=’Delete(“
+ val.ID + “)’>Delete</a>” +

“</td></tr>”);

});

}

}

$(function () {

bind();

});

</script>

</asp:Content>

 

2.     Add Class Student.cs (Code Firs)

 

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using
System.Runtime.Serialization;

using System.Web;

 

namespace FEB.Model

{

publicclassStudent

{

[ScaffoldColumn(false)]

publicint ID {
get; set; }

 

[Required, StringLength(100)]

publicstring Name
{
get; set; }

[Required, StringLength(100)]

publicstring
Parent {
get; set; }

 

publicint? Age
{
get; set; }

 

publicDateTime?
CreateDate {
get; set; }

}

}

 

3.  Add DBContext Class

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.Entity;

namespace FEB.Model

{

publicclassMyContext : DbContext

{

public
MyContext()

: base(“mycon”)//connection
Name

{

}

publicDbSet<Student>
Students {
get; set; }

}

}

4.  Add Web Api Controller

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

using FEB.Model;

 

namespace FEB.Controller

{

publicclassStudentController : ApiController

{

privateMyContext
context =
newMyContext();

privateList<Student>
students;

public
StudentController()

{

students = context.Students.ToList();

}

// GET
api/<controller>

publicIEnumerable<Student>
Get()

{

return
students;

}

 

// GET
api/<controller>/5

publicStudent Get(int id)

{

Student stu
= students.FirstOrDefault(z => z.ID == id);

return stu;

}

publicList<Student>
Get(
string text)

{

List<Student>
resuts =
newList<Student>();

 

var stud
= students.Where(x => x.Name.StartsWith(text)).ToList();

foreach (var x in
stud)

{

resuts.Add(newStudent()

{

ID = x.ID,

Name = x.Name,

Parent = x.Parent

});

}

 

 

 

return
resuts.ToList();

}

// POST
api/<controller>

publicvoid
Post([
FromBody]Student value)

{

using (var db =
context)

{

var
count =

db.Students.Count(a =>
a.Name == value.Name && a.Parent == value.Parent && a.Age ==
value.Age);

if
(count == 0)

{

Student stu
=
newStudent();

stu.Name = value.Name;

stu.Parent = value.Parent;

stu.Age = Convert.ToInt32(value.Age);

stu.CreateDate = DateTime.Now;

db.Students.Add(stu);

db.SaveChanges();

}

 

}

}

 

// PUT
api/<controller>/5

publicvoid Put(int id,
[
FromBody]Student value)

{

using (var db =
context)

{

Student stu
= students.FirstOrDefault(z => z.ID == id);

if (stu
!=
null)

{

stu.Name = value.Name;

stu.Parent = value.Parent;

stu.Age = Convert.ToInt32(value.Age);

}

db.SaveChanges();

}

}

 

// DELETE
api/<controller>/5

publicvoid
Delete(
int id)

{

using (var db =
context)

{

Student stu
= students.FirstOrDefault(z => z.ID == id);

db.Students.Remove(stu);

db.SaveChanges();

}

}

}

}

5.  MyRoute.cs (Routing)

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Routing;

using System.Web.Http;

 

namespace FEB.Code

{

publicclassMyRoute

{

publicstaticvoid
Route(
RouteCollection route)

{

route.MapHttpRoute(name: “DefaultApi”,
routeTemplate:
“api/{controller}/{id}”,

defaults: new {id
=
RouteParameter.Optional});

 

route.MapPageRoute(“StudentPage”, “student”, “~/Pages/StudentPage.aspx”);

}

}

}

6.  Global.asax

 

protectedvoid
Application_Start(
object sender, EventArgs e)

{

MyRoute.Route(RouteTable.Routes);

}

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: