Skip to content
Image

Read Text File Data in C#:-

ReadFile

C# Asp.Net, Code First with Mapping, Web Api Controller, KnockOut js and BootStrap.

Home.Master.aspx

<%@MasterLanguage=”C#”AutoEventWireup=”true”CodeBehind=”Home.master.csInherits=”EFCodeFirstWithMapping.Home%>

<!DOCTYPE html>


<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

<title></title>

<linkhref=”/Scripts/bootstrap/css/bootstrap.css”rel=”stylesheet/>

<linkhref=”/Scripts/bootstrap/css/bootstrap-responsive.css”rel=”stylesheet/>

<scriptsrc=”/Scripts/js/jquery-2.0.0.min.js”></script>

<scriptsrc=”/Scripts/js/knockout-2.2.1.js”></script>

<scriptsrc=”/Scripts/bootstrap/js/bootstrap.js”></script>

<asp:ContentPlaceHolderID=”head”runat=”server”>

</asp:ContentPlaceHolder>

</head>

<body>

<formid=”form1″runatspan>=”server”>

<div>

<asp:ContentPlaceHolderID=”MainContentrunat=”server”>

</asp:ContentPlaceHolder>

</div>

 

</form>

 

<asp:ContentPlaceHolderID=”ScriptContentrunat=”server”>

</asp:ContentPlaceHolder>

</body>

</html>

 

CodeFirstWithMapping.aspx

<%@PageTitle=””Language=”C#”MasterPageFile=”~/Home.MasterAutoEventWireup=”true”CodeBehind=”CodeFirstWithMapping.aspx.csInherits=”EFCodeFirstWithMapping.CodeFirstWithMapping%>

 

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

</asp:Content>

<asp:ContentID=”Content2″ContentPlaceHolderID=”MainContentrunat=”server”>

<tablewidth=”100%”class=”table”>

<tr>

<tdwidth=”50%”valign=”top”>

<table>

<tr>

<tdvalign=”top”>

<tableid=”registerTable“>

<tr>

<td>Name</td>

<td>

<asp:TextBoxrunat=”server”data-bind=”value:NameID=”NameTextBox“></asp:TextBox></td>

</tr>

<tr>

<td>Email</td>

<td>

<asp:TextBoxTextMode=”Email”data-bind=”value:EmailIDrunat=”server”ID=”EmailTextBox“></asp:TextBox></td>

</tr>

<tr>

<td>Password</td>

<td>

<asp:TextBoxrunat=”server”data-bind=”value:PasswordTextMode=”Password”ID=”PasswordTextBox“></asp:TextBox></td>

</tr>

<tr>

<td>Address</td>

<td>

<asp:TextBoxrunat=”server”data-bind=”value:AddressTextMode=”MultiLineID=”AddressTextBox“></asp:TextBox></td>

</tr>

<tr>

<td>

<asp:Buttonclass=”btnID=”SaveByCoderunat=”server”Text=”SaveByCodeOnClick=”SaveByCode_Click/></td>

<td>

<inputclass=”btntype=”submit”value=”SaveByApidata-bind=”click: regUser/></td>

</tr>

</table>

</td>

<tdvalign=”top”>

<tableid=”loginTable“>

 

<tr>

<td>Email</td>

<td>

<asp:TextBoxdata-bind=”value:EmailIdrunat=”server”ID=”LoginIdTextBoxplaceholder=”email
address”></
asp:TextBox></td>

</tr>

<tr>

<td>Password</td>

<td>

<asp:TextBoxrunat=”server”data-bind=”value:PasswordID=”LoginPasswordTextBoxTextMode=”Password”placeholder=”password”></asp:TextBox></td>

</tr>

 

<tr>

<td></td>

<td>

<buttontype=”button”id=”loginBtnclass=”btn
btn-primary”
data-loading-text=”Loading…”data-bind=”click: loginUser“>login</button>

 

</td>

</tr>

</table>

</td>

</tr>

<tr>

<tdcolspan=”2″>Binding with Code Behind Grid<br/>

<asp:GridViewrunat=”server”ID=”BindGrid“></asp:GridView>

</td>

</tr>

<tr>

<tdcolspan=”2″>Binding with API, Knockout js<br/>

<tableid=”gvDetailsborder=”1″></table>

</td>

</tr>

</table>

</td>

<tdwidth=”50%”valign=”top”>

<tableid=”cityTable“>

<tr>

<td>City Name

</td>

<td>

<inputtype=”text”data-bind=”value: Name/></td>

</tr>

<tr>

<td></td>

<td>

<inputtype=”submit”class=”btn
btn-primary”
id=”addCityBtndata-loading-text=”Wait…”data-bind=”click: saveCityvalue=”Add City”/></td>

</tr>

<tr>

<tdvalign=”top”>All City

</td>

<tdclass=”container”>

<selectdata-bind=”options: AllCities,
optionsText:
‘Name’,
value:
‘ID’, optionsCaption:
‘Choose…’“></select>

<divdata-bind=”foreach: AllCities“>

<spandata-bind=”text: $data.Name“></span>

<ahref=”javascript:void(0)”data-toggle=”tooltip”title=”Delete City”data-bind=”click: deleteCitystyle=”color: red”>X</a>

<br/>

</div>

</td>

</tr>

</table>

</td>

</tr>

</table>

 

 

</asp:Content>

<asp:ContentID=”Content3″ContentPlaceHolderID=”ScriptContentrunat=”server”>

<scripttype=”text/javascript“>

var loginModel
= {

EmailId: ko.observable(),

Password: ko.observable(),

};

var regModel
= {

Name: ko.observable(),

Password: ko.observable(),

EmailID: ko.observable(),

Address: ko.observable(),

};

var cityModel
= {

Name: ko.observable(),

AllCities: ko.observableArray([''])

};

 

ko.applyBindings(loginModel, document.getElementById(loginTable));

ko.applyBindings(regModel, document.getElementById(registerTable));

ko.applyBindings(cityModel, document.getElementById(cityTable));

 

function loginUser()
{

var user = ko.toJS(loginModel);

setTimeout(function () {

$.post(“/api/login”, user, function (item) {

$(‘#loginBtn).button(‘reset’);

});

},
3000);

 

}

 

function regUser()
{

var user = ko.toJS(regModel);

$.post(“/api/register”, user, function () {

BindGrid();

});

}

 

function saveCity()
{

var user = ko.toJS(cityModel);

setTimeout(function () {

$.post(“/api/city”, user, function () {

loadCity();

$(‘#addCityBtn).button(‘reset’);

 

});

},
2000);

 

}

 

function deleteCity(item)
{

console.log(item);

$.ajax({

url: “/api/city/” + item.ID,

type: “Delete”,

success: function
() {

loadCity();

},

});

}

function BindGrid()
{

 

$(“#gvDetails).empty();

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

“<th>Name</th>” +

“<th>EmailID</th>” +

“<th>Address</th>” +

“</tr>”);

$.getJSON(“/api/register”, function (data) {

$.each(data, function (index, item) {

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

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

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

+ item.EmailID + “</td><td>”

+ item.Address + “</td>”

+ “</tr>”);

});

});

 

 

}

 

 

function loadCity()
{

cityModel.AllCities.removeAll();

$.getJSON(“/api/city”, function (data) {

$.each(data, function (index, item) {

cityModel.AllCities.push(item);

});

});

 

 

}

$(function () {

loadCity();

BindGrid();

});

 

 

 

$(‘#loginBtn).click(function () {

var btn
= $(
this);

btn.button(‘loading’);

/* setTimeout(function() {

btn.button(‘reset’);

}, 3000);*/

});

 

$(‘#addCityBtn).click(function () {

$(this).button(‘loading’);

});

</script>

</asp:Content>


 

CodeFirstWithMapping.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using EFCodeFirstWithMapping.Utilities;

 

namespace EFCodeFirstWithMapping

{

publicpartialclassCodeFirstWithMapping : System.Web.UI.Page

{

protectedvoid Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

Bind();

}

 

}

 

protectedvoid SaveByCode_Click(object sender, EventArgs e)

{

if (Page.IsValid)

{

if (!String.IsNullOrEmpty(NameTextBox.Text)
&& !
String.IsNullOrEmpty(EmailTextBox.Text)
&&

!String.IsNullOrEmpty(PasswordTextBox.Text))

{

MyContext db
=
newMyContext();

User user = newUser();

user.Name = NameTextBox.Text;

user.EmailID = EmailTextBox.Text;

user.Password = PasswordTextBox.Text;

user.CreateDate = DateTime.Now;

user.IsDeleted = false;

user.Address = AddressTextBox.Text;

db.Users.Add(user);

db.SaveChanges();

Bind();

}

}/o:p>

 

 

}

 

privatevoid Bind()

{

MyContext db
=
newMyContext();

BindGrid.DataSource = db.Users.ToList();

BindGrid.DataBind();

}

}

}

 

RouteUrl

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Routing;

using System.Web.Http;

namespace EFCodeFirstWithMapping.Utilities

{

publicclassRouteUrl

{

publicstaticvoid RegisterRoute(RouteCollection route)

{

route.MapPageRoute(“Home”, “”, “~/CodeFirstWithMapping.aspx”);

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

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

 

}

}

}

 

Global.asax

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Routing;

using System.Web.Security;

using System.Web.SessionState;

using EFCodeFirstWithMapping.Utilities;

 

namespace EFCodeFirstWithMapping

{

publicclassGlobal : System.Web.HttpApplication

{

 

protectedvoid Application_Start(object sender, EventArgs e)

{

RouteUrl.RegisterRoute(RouteTable.Routes);

}

 

}

}

MyContext.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.Entity;

namespace EFCodeFirstWithMapping.Utilities

{

publicclassMyContext : DbContext

{

public MyContext()

: base(MyConnection)

{

 

}

 

publicDbSet<User> Users { get; set; }

publicDbSet<City> Cities { get; set; }

}

}

 

User.cs

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

 

namespace EFCodeFirstWithMapping.Utilities

{

publicclassUser

{

[Key]

[Required]

publicint ID { get; set; }

 

[Display(Name = "Name", Description = "First Name + Last
Name."
)]

[Required(ErrorMessage = "First Name is
required."
)]

[RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$”, ErrorMessage =

“Numbers and special
characters are not allowed in the name.”
)]

publicstring Name { get; set; }

 

[Required]

[DataType(DataType.EmailAddress)]

publicstring EmailID
{
get; set; }

publicstring Password { get; set; }

publicDateTime CreateDate
{
get; set; }

publicbool IsDeleted
{
get; set; }

publicstring Address { get; set; }

 

}

}

UserMapping.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.Entity.ModelConfiguration;

namespace EFCodeFirstWithMapping.Utilities

{

publicclassUserMapping : EntityTypeConfiguration<User>

{

public UserMapping()

{

Property(p => p.ID).IsRequired().HasColumnName(“ID”);

Property(p => p.Name).IsRequired().HasMaxLength(50).HasColumnName(“Name”);

Property(p => p.EmailID).IsRequired().HasMaxLength(50).HasColumnName(“EmailID”);

Property(p => p.Password).IsRequired().HasMaxLength(50).HasColumnName(“Password”);

Property(p => p.CreateDate).IsRequired().HasColumnName(CreateDate);

Property(p => p.IsDeleted).IsRequired().HasColumnName(IsDeleted);

Property(p => p.Address).IsOptional();

ToTable(“Users”);


}

}

}

RegisterModel.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace EFCodeFirstWithMapping.Utilities

{

publicclassRegisterModel

{

publicstring Name { get; set; }

publicstring EmailID
{
get; set; }

publicstring Password { get; set; }

publicstring Address { get; set; }

}

}

City.cs

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

 

namespace EFCodeFirstWithMapping.Utilities

{

publicclassCity

{

[Key]

[Required]

publicint ID { get; set; }

 

[Required(ErrorMessage = "Please Enter
City"
)]

publicstring Name { get; set; }

 

[Required]

[DataType(DataType.DateTime)]

publicDateTime CreateDate
{
get; set; }

 

 

}

}

CityMapping.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.Entity.ModelConfiguration;

namespace EFCodeFirstWithMapping.Utilities

{

publicclassCityMapping : EntityTypeConfiguration<City>

{

public CityMapping()

{

Property(x => x.ID).IsRequired();

Property(x => x.Name).IsRequired();

Property(x => x.CreateDate).IsRequired();

ToTable(“Cities”);

}

}

}

CityModel.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace EFCodeFirstWithMapping.Utilities

{

publicclassCityModel

{

publicint ID { get; set; }

publicstring Name { get; set; }

}

}

LoginModel.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace EFCodeFirstWithMapping.Utilities

{

publicclassLoginModel

{

publicstring EmailId
{
get; set; }

publicstring Password { get; set; }

}

}

RegisterController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

using EFCodeFirstWithMapping.Utilities;

 

namespace EFCodeFirstWithMapping.Controller

{

publicclassRegisterController : ApiController

{

privateMyContext db
=
newMyContext();

 

publicIEnumerable<User> GetAll()

{

return db.Users;

}

 

publicvoid Post(RegisterModel model)

{

if (!String.IsNullOrEmpty(model.Name)
&& !
String.IsNullOrEmpty(model.EmailID)&&!String.IsNullOrEmpty(model.Password))

{

User user = newUser();

user.Name = model.Name;

user.EmailID = model.EmailID;

user.Password = model.Password;

user.Address = model.Address;

user.IsDeleted = false;

user.CreateDate
=
DateTime.Now;

db.Users.Add(user);

db.SaveChanges();

}

 

}

}

}

CityController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

using EFCodeFirstWithMapping.Utilities;

 

namespace EFCodeFirstWithMapping.Controller

{

publicclassCityController : ApiController

{

publicIEnumerable<CityModel> GetAll()

{

MyContext db
=
newMyContext();

return db.Cities.Select(x
=>
newCityModel()

{

ID = x.ID,

Name = x.Name

}).ToList();

}

publicvoid Post(CityModel model)

{

 

if (!String.IsNullOrEmpty(model.Name))

{

MyContext db
=
newMyContext();

if (!db.Cities.Any(x
=> x.Name == model.Name))

{

City city
=
newCity();

city.Name = model.Name;

city.CreateDate = DateTime.Now;

db.Cities.Add(city);

db.SaveChanges();

}

}

 

 

}

 

publicvoid Delete(int id)

{

MyContext db
=
newMyContext();

City city
= db.Cities.FirstOrDefault(x => x.ID == id);

db.Cities.Remove(city);

db.SaveChanges();

 

}

}

}

LoginController.cs

using System.Linq;

using System.Web.Http;

using EFCodeFirstWithMapping.Utilities;

 

namespace EFCodeFirstWithMapping.Controller

{

publicclassLoginController : ApiController

{

privateMyContext db
=
newMyContext();

 

publicbool Post(LoginModel model)

{

IQueryable<User> users = db.Users;

if (users.Any(x
=> x.EmailID == model.EmailId
&& x.Password == model.Password))

{

returntrue;

}

else

{

returnfalse;

}

}

}

}

Web.config

<?xmlversion=1.0encoding=utf-8?>

<!–

For more
information on how to configure your ASP.NET application, please visit

http://go.microsoft.com/fwlink/?LinkId=169433

–>

<configuration>

<configSections>

<!–
For more information on Entity Framework configuration, visit
http://go.microsoft.com/fwlink/?LinkID=237468
–>

<sectionname=entityFrameworktype=System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
requirePermission=false />

</configSections>

<system.web>

<compilationdebug=truetargetFramework=4.5 />

<httpRuntimetargetFramework=4.5 />

</system.web>

<entityFramework>

<defaultConnectionFactorytype=System.Data.Entity.Infrastructure.LocalDbConnectionFactory,
EntityFramework
>

<parameters>

<parametervalue=v11.0 />

</parameters>

</defaultConnectionFactory>

</entityFramework>

<connectionStrings>

<addname=MyConnectionconnectionString=Data Source=local;Initial Catalog=******db;Integrated
Security=false;MultipleActiveResultSets=True;Persist Security Info=True;User
ID=*****;pwd=*****;
providerName=System.Data.SqlClient />

</connectionStrings>

<system.webServer>

<handlers>

<removename=ExtensionlessUrlHandler-ISAPI-4.0_32bit />

<removename=ExtensionlessUrlHandler-ISAPI-4.0_64bit />

<removename=ExtensionlessUrlHandler-Integrated-4.0 />

<addname=ExtensionlessUrlHandler-ISAPI-4.0_32bitpath=*.verb=GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONSmodules=IsapiModulescriptProcessor=%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dllpreCondition=classicMode,runtimeVersionv4.0,bitness32responseBufferLimit=0 />

<addname=ExtensionlessUrlHandler-ISAPI-4.0_64bitpath=*.verb=GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONSmodules=IsapiModulescriptProcessor=%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dllpreCondition=classicMode,runtimeVersionv4.0,bitness64responseBufferLimit=0 />

<addname=ExtensionlessUrlHandler-Integrated-4.0path=*.verb=GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONStype=System.Web.Handlers.TransferRequestHandlerpreCondition=integratedMode,runtimeVersionv4.0 />

</handlers>

</system.webServer>

</configuration>

–>

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

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

}

Follow

Get every new post delivered to your Inbox.