Introduction
This article shows how to perform CRUD Operation in ASP.NET MVC, using AJAX and Bootstrap. In previous ASP.NET MVC tutorials of this series, we saw,
- Creating First Application In ASP.NET MVC
- Pass Parameter Or Query String In Action Method In ASP.NET MVC
- Passing Data from Controller To View In ASP.NET MVC
- Strongly Typed View Vs Dynamically Typed View In ASP.NET MVC
- Working With Built-In HTML Helper Classes In ASP.NET MVC
- Inline and Custom HTML Helpers In ASP.NET MVC
What is AJAX and Bootstrap?
AJAX (Asynchronous JavaScript and XML) in the Web Application is used to update parts of the existing page and to retrieve the data from the Server asynchronously. AJAX improves the performance of the Web Application and makes the Application more interactive.
Bootstrap is one of the most popular HTML, CSS and JS frameworks for developing responsive, mobile first projects on the Web.
Let’s Begin
Create a new ASP.NET Web Application.

Select Empty ASP.NET MVC template and click OK.

Now, right-click on the project and click Manage NuGet Packages.

Search for Bootstrap and then click Install button.

After installing the package, you will see the Content and Scripts folder being added in your Solution Explorer.

Now, create a database and add a table (named Employee). The following is the schema for creating a table Employee:

After the table creation, create the stored procedures for Select, Insert, Update and Delete operations.
-- Select Employees
CREATE PROCEDURE SelectEmployee
AS
BEGIN
SELECT * FROM Employee;
END
-- Insert and Update Employee
CREATE PROCEDURE InsertUpdateEmployee
(
@Id INTEGER,
@Name NVARCHAR(50),
@Age INTEGER,
@State NVARCHAR(50),
@Country NVARCHAR(50),
@Action VARCHAR(10)
)
AS
BEGIN
IF @Action = 'Insert'
BEGIN
INSERT INTO Employee (Name, Age, [State], Country) VALUES (@Name, @Age, @State, @Country);
END
IF @Action = 'Update'
BEGIN
UPDATE Employee
SET Name = @Name, Age = @Age, [State] = @State, Country = @Country
WHERE EmployeeID = @Id;
END
END
-- Delete Employee
CREATE PROCEDURE DeleteEmployee
(
@Id INTEGER
)
AS
BEGIN
DELETE FROM Employee WHERE EmployeeID = @Id;
END
Right click on Modal Folder and add Employee.cs class.
Employee.cs Code
public class Employee
{
public int EmployeeID { get; set; } // Property for the unique identifier of the employee
public string Name { get; set; } // Property for the name of the employee
public int Age { get; set; } // Property for the age of the employee
public string State { get; set; } // Property for the state where the employee resides
public string Country { get; set; } // Property for the country where the employee resides
}
Now, add another class in Modal Folder named as EmployeeDB.cs for the database related operations. In this example, I am going to use ADO.NET to access the data from the database.
public class EmployeeDB
{
//declare connection string
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
//Return list of all Employees
public List<Employee> ListAll()
{
List<Employee> lst = new List<Employee>();
using(SqlConnection con=new SqlConnection(cs))
{
con.Open();
SqlCommand com = new SqlCommand("SelectEmployee",con);
com.CommandType = CommandType.StoredProcedure;
SqlDataReader rdr = com.ExecuteReader();
while(rdr.Read())
{
lst.Add(new Employee {
EmployeeID=Convert.ToInt32(rdr["EmployeeId"]),
Name=rdr["Name"].ToString(),
Age = Convert.ToInt32(rdr["Age"]),
State = rdr["State"].ToString(),
Country = rdr["Country"].ToString(),
});
}
return lst;
}
}
//Method for Adding an Employee
public int Add(Employee emp)
{
int i;
using(SqlConnection con=new SqlConnection(cs))
{
con.Open();
SqlCommand com = new SqlCommand("InsertUpdateEmployee", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Id",emp.EmployeeID);
com.Parameters.AddWithValue("@Name", emp.Name);
com.Parameters.AddWithValue("@Age", emp.Age);
com.Parameters.AddWithValue("@State", emp.State);
com.Parameters.AddWithValue("@Country", emp.Country);
com.Parameters.AddWithValue("@Action", "Insert");
i = com.ExecuteNonQuery();
}
return i;
}
//Method for Updating Employee record
public int Update(Employee emp)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand com = new SqlCommand("InsertUpdateEmployee", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Id", emp.EmployeeID);
com.Parameters.AddWithValue("@Name", emp.Name);
com.Parameters.AddWithValue("@Age", emp.Age);
com.Parameters.AddWithValue("@State", emp.State);
com.Parameters.AddWithValue("@Country", emp.Country);
com.Parameters.AddWithValue("@Action", "Update");
i = com.ExecuteNonQuery();
}
return i;
}
//Method for Deleting an Employee
public int Delete(int ID)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand com = new SqlCommand("DeleteEmployee", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Id", ID);
i = com.ExecuteNonQuery();
}
return i;
}
}
Right click on Controllers folder, add an Empty Controller and name it as HomeController.

Now, open HomeController and add the following action methods.
public class HomeController : Controller
{
EmployeeDB empDB = new EmployeeDB();
// GET: Home
public ActionResult Index()
{
return View();
}
public JsonResult List()
{
return Json(empDB.ListAll(),JsonRequestBehavior.AllowGet);
}
public JsonResult Add(Employee emp)
{
return Json(empDB.Add(emp), JsonRequestBehavior.AllowGet);
}
public JsonResult GetbyID(int ID)
{
var Employee = empDB.ListAll().Find(x => x.EmployeeID.Equals(ID));
return Json(Employee, JsonRequestBehavior.AllowGet);
}
public JsonResult Update(Employee emp)
{
return Json(empDB.Update(emp), JsonRequestBehavior.AllowGet);
}
public JsonResult Delete(int ID)
{
return Json(empDB.Delete(ID), JsonRequestBehavior.AllowGet);
}
}
Right click on the Index action method of HomeController and click on Add View. As we are going to use Bootstrap and AJAX, we have to add their relative Scripts and CSS references in the head section of the view. I have also added employee.js, which will contain all AJAX code, that are required for CRUD operation.
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/employee.js"></script>
Add the code, given below, in Index.cshtml view.
<p class="container">
<h2>Employees Record</h2>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="clearTextBox();">
Add New Employee
</button><br /><br />
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>State</th>
<th>Country</th>
<th>Action</th>
</tr>
</thead>
<tbody class="tbody">
<!-- Employee records will be populated here -->
</tbody>
</table>
</p>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" id="myModalLabel">Add Employee</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="EmployeeId">ID</label>
<input type="text" class="form-control" id="EmployeeID" placeholder="Id" disabled="disabled" />
</div>
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" id="Name" placeholder="Name" />
</div>
<div class="form-group">
<label for="Age">Age</label>
<input type="text" class="form-control" id="Age" placeholder="Age" />
</div>
<div class="form-group">
<label for="State">State</label>
<input type="text" class="form-control" id="State" placeholder="State" />
</div>
<div class="form-group">
<label for="Country">Country</label>
<input type="text" class="form-control" id="Country" placeholder="Country" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnAdd" onclick="return Add();">Add</button>
<button type="button" class="btn btn-primary" id="btnUpdate" style="display:none;" onclick="Update();">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
In the code, given above, we have added a button for adding New Employee. On clicking, It will open the modal dialog box of the bootstrap, which contains several fields of the employees for saving. We have also added a table, which will be populated with the use of AJAX.
Employee.js Code
// Load Data in Table when document is ready
$(document).ready(function () {
loadData();
});
// Load Data function
function loadData() {
$.ajax({
url: "/Home/List",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.EmployeeID + '</td>';
html += '<td>' + item.Name + '</td>';
html += '<td>' + item.Age + '</td>';
html += '<td>' + item.State + '</td>';
html += '<td>' + item.Country + '</td>';
html += '<td><a href="#" onclick="return getbyID(' + item.EmployeeID + ')">Edit</a> | <a href="#" onclick="Delele(' + item.EmployeeID + ')">Delete</a></td>';
html += '</tr>';
});
$('.tbody').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
// Add Data Function
function Add() {
var res = validate();
if (res == false) {
return false;
}
var empObj = {
EmployeeID: $('#EmployeeID').val(),
Name: $('#Name').val(),
Age: $('#Age').val(),
State: $('#State').val(),
Country: $('#Country').val()
};
$.ajax({
url: "/Home/Add",
data: JSON.stringify(empObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
loadData();
$('#myModal').modal('hide');
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
// Function for getting the Data Based upon Employee ID
function getbyID(EmpID) {
$('#Name').css('border-color', 'lightgrey');
$('#Age').css('border-color', 'lightgrey');
$('#State').css('border-color', 'lightgrey');
$('#Country').css('border-color', 'lightgrey');
$.ajax({
url: "/Home/getbyID/" + EmpID,
type: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (result) {
$('#EmployeeID').val(result.EmployeeID);
$('#Name').val(result.Name);
$('#Age').val(result.Age);
$('#State').val(result.State);
$('#Country').val(result.Country);
$('#myModal').modal('show');
$('#btnUpdate').show();
$('#btnAdd').hide();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
return false;
}
// Function for updating employee's record
function Update() {
var res = validate();
if (res == false) {
return false;
}
var empObj = {
EmployeeID: $('#EmployeeID').val(),
Name: $('#Name').val(),
Age: $('#Age').val(),
State: $('#State').val(),
Country: $('#Country').val(),
};
$.ajax({
url: "/Home/Update",
data: JSON.stringify(empObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
loadData();
$('#myModal').modal('hide');
$('#EmployeeID').val("");
$('#Name').val("");
$('#Age').val("");
$('#State').val("");
$('#Country').val("");
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
// Function for deleting employee's record
function Delele(ID) {
var ans = confirm("Are you sure you want to delete this Record?");
if (ans) {
$.ajax({
url: "/Home/Delete/" + ID,
type: "POST",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (result) {
loadData();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
}
// Function for clearing the textboxes
function clearTextBox() {
$('#EmployeeID').val("");
$('#Name').val("");
$('#Age').val("");
$('#State').val("");
$('#Country').val("");
$('#btnUpdate').hide();
$('#btnAdd').show();
$('#Name').css('border-color', 'lightgrey');
$('#Age').css('border-color', 'lightgrey');
$('#State').css('border-color', 'lightgrey');
$('#Country').css('border-color', 'lightgrey');
}
Build and run the Application.
Adding a Record (Preview)

Editing a Record (Preview)

Delete a Record(Preview)


waqas bangashPosted Jan 8, 2023, 5:59 AM
Dear i downloaded your application but its not running successfully. since it was developed in 2016 but i am using VS 2022. cant see Database Connections code. where database name is mentioned. please assist.
Emmmanuel FIADUFEPosted Nov 21, 2022, 11:54 PM
Please how do you apply DataTable to this tutorial. Thank you
Emmmanuel FIADUFEPosted Oct 29, 2022, 6:10 PM
Good article sir, please can you show me how to add sweetalert to the delete and edit button
Manoj KumarPosted Mar 29, 2022, 5:07 AM
I couldn't able to update the data
Manoj KumarPosted Mar 23, 2022, 4:59 AM
Thanks for the article
Srinivas BankalaPosted Nov 25, 2021, 10:25 AM
Hi sir this example was an amazing it is very helpful to others with easy way and easy to understand. I Need small help sir How can we implement Search functionality (by searching name) without Entity framework. Could you please help me sir?
Ajitkumar RajputPosted Jun 18, 2021, 5:28 AM
I got the error data undefined
Ajitkumar RajputPosted Jun 18, 2021, 5:22 AM
Function GetByID(ID) { $.ajax({ type: "GET", url: '@Url.Action("GetDataByID", "Transporter")/' + ID, contentType: "application/json;charset=UTF-8", dataType: "json", success: function (data) { alert("Get data " + data.TransporterName); $('#transporterModal').modal('show'); $("#TransporterName").val("New values"); $('#OwnerName').val(data.OwnerName); $('#TAddressLine1').val(data.TAddressLine1); $('#TAddressLine2').val(data.TAddressLine2); $('#City').val(data.City); $('#State').val(data.State); $('#Pincode').val(data.Pincode); $('#PhoneNo').val(data.PhoneNo); $('#MobileNo').val(data.MobileNo); $('#EmailID').val(data.EmailID); $('#Status').val(data.Status); $('#MobileNo').val(data.MobileNo); }, error: function (errormessage) { alert(errormessage.responseText); } }); }
Ajitkumar RajputPosted Jun 18, 2021, 5:22 AM
Dear Data not fetch by this method please help me
Tâm VănPosted May 6, 2021, 8:44 AM
If it is difficult, you can refer to the following source code : https://github.com/tamlv-lqdgroup/CrudAjax Thanks for your code.
Julian VargasPosted Dec 16, 2020, 10:32 AM
Thanks for your code is very helpful to me, I have a question, how can we put filters to the grid??
Venugopal ReddyPosted Oct 27, 2020, 4:04 AM
Please provide in entity framework (code first approach)
John mikePosted Aug 27, 2020, 1:31 AM
Thank you. It was very inspirational in my project. One thing is in line 70, typr: "GET" should be type:"GET"
Sujit Kumar MishraPosted Mar 2, 2020, 4:29 AM
Every code run Successfully , but "function getbyID(EmpID)" function not work Please Help me. It is show error. & How to resolve
Shah KhanPosted Feb 19, 2020, 5:23 AM
Thanks for sharing your skills <3
Kishan HirparaPosted Jul 13, 2019, 6:15 AM
How do i apply datatable in this code for pagging ,sorting and searching
Atta KumahPosted Apr 1, 2019, 10:33 PM
Wonderful Presentation.Thanks Very much ! great working coding
juan manuel rodriguezPosted Mar 29, 2019, 12:36 PM
Because the operation insert and update are sharing, it was necessary set a zero value like parameter when you use insert or add , and this form the solution act
redar ismailPosted Mar 26, 2019, 1:29 PM
Can you use Validate.js instead doing validation.. the code is working but I have still problems in handling validation inside Edit .. I am using Validate.js
Abhijit ParidaPosted Mar 14, 2019, 6:24 AM
Nothing to say osm sir
Ahmad BrohiPosted Dec 18, 2018, 12:27 AM
I have a error in mapping employobj with mvc controller empoloyee it always showing null why
Ajay VishwakarmaPosted Nov 30, 2018, 5:00 AM
Nice artical ! great working coding
Najmul IslamPosted Oct 17, 2018, 1:27 PM
Id not find By Controller...and throw the exception
Najmul IslamPosted Oct 17, 2018, 1:26 PM
Sir I try your code... Every code run Successfully , but "function getbyID(EmpID)" function not work Please Help me. It is show error.
Nitin ShakyaPosted Oct 3, 2018, 1:06 AM
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Employee.aspx.cs" Inherits="TestSagar1.Employee" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="jquery-3.2.1.min.js"></script> <script type="text/javascript"> var idd = 0; $(document).ready(function () { $("th:even").css('background-color', 'blue'); $("th:odd").css("background-color", "grey"); Getshow(); CityGet(); Country(); $("#txtbcode").attr("disabled", true); }); function InsertData() { $.ajax({ url: 'Employee.aspx/Insert', type: 'post', contentType: 'application/json;charset=utf-8', dataType: 'json', data: "{B: '" + $("#txtcperson").val() + "', C: '" + $("#txtbname").val() + "',D: '" + $("#txtemail").val() + "',E: '" + $("#txtsname").val() + "',F: '" + ($("#chkhub").is(':checked') == true ? 1 : 0) + "',G: '" + $("#txtaddress").val() + "',H: '" + ($("#chkvender").is(':checked') == true ? 1 : 0) + "',I: '" + ($("#chkactive").is(':checked') == true ? 1 : 0) + "',J: '" + $("#ddlcity").val() + "',K: '" + $("#txtpin").val() + "',L: '" + $("#txtzone").val() + "',M: '" + idd + "'}", success: function (_dt) { _dt = JSON.parse(_dt.d); $("#txtbcode").val(_dt); alert('operation success'); Getshow(); $("#btnsave").val("Save") }, error: function () { alert('operation error'); }, }); } function EditData(eid) { $.ajax({ url: 'Employee.aspx/Edit', type: 'post', contentType: 'application/json;charset=utf-8', dataType: 'json', data: "{A: '" + eid + "'}", success: function (_dt) { _dt = JSON.parse(_dt.d); $("#txtbname").val(_dt[0].Bname); $("#txtaddress").val(_dt[0].address); $("#txtemail").val(_dt[0].Email); $("#txtsname").val(_dt[0].Sname); $("#txtcperson").val(_dt[0].ContactPerson); $("#txtpin").val(_dt[0].pincode); $("#txtzone").val(_dt[0].Zone); $("#ddlcity").val(_dt[0].city); $("input[type=checkbox][value='"+ _dt[0].active +"']").prop("checked", true); idd = eid; $("#btnsave").val("Update"); }, error: function () { alert('edit error !!'); } }); } function DeleteData(eid) { $.ajax({ url: 'Employee.aspx/Delete', type: 'post', contentType: 'application/json;charset=utf-8', dataType: 'json', data: "{A: '" + eid + "'}", success: function () { alert('Delete success'); Getshow(); }, error: function () { alert('Delete error !!'); } }); } function CityGet() { $.ajax({ url: 'Employee.aspx/City', type: 'post', contentType: 'application/json;charset=utf-8', dataType: 'json', data: "{}", success: function (_dt) { _dt = JSON.parse(_dt.d); for (var i = 0; i < _dt.length; i++) { $("#ddlcity").append($('<option/>').attr("value", _dt[i].cid).text(_dt[i].cname)); } }, error: function () { alert('get country error !!'); } }); } function Country() { $.ajax({ url: 'Employee.aspx/Country', type: 'post', contentType: 'application/json;charset=utf-8', dataType: 'json', data: "{}", success: function (_dt) { _dt = JSON.parse(_dt.d); for (var i = 0; i < _dt.length; i++) { $("#ddlcountry").append($('<option/>').attr("value", _dt[i].cid).text(_dt[i].cname)); } }, error: function () { alert('get city error !!'); } }); } function Getshow() { $.ajax({ url: 'Employee.aspx/Getdata', type: 'post', contentType: 'application/json;charset=utf-8', dataType: 'json', data: "{}", success: function (_dt) { _dt = JSON.parse(_dt.d); $("#tbl").find("tr:gt(0)").remove(); for (var i = 0; i < _dt.length; i++) { $("#tbl").append('<tr><td>' + _dt[i].ContactPerson + '</td> , <td>' + _dt[i].Bname + '</td> <td>' + _dt[i].address + '</td> <td>' + _dt[i].Email + '</td> <td>' + _dt[i].Sname + '</td> <td>' + (_dt[i].vender == "1 " ? "yes" : "NO") + '</td> <td>' + (_dt[i].hub == "1" ? "yes" : "No") + '</td> <td>' + (_dt[i].active == "1" ? "yes" : "no") + '</td> <td>' + _dt[i].cname + '</td> <td>' + _dt[i].pincode + '</td> <td>' + _dt[i].Zone + '</td> <td> <input type="button" id="btnedit" value="Edit" onclick="EditData(' + _dt[i].eid + ')" /> </td> <td> <input type="button" id="btndelete" value="Delete" onclick="DeleteData(' + _dt[i].eid + ')" /> </td> </tr>'); $("btnsave").val("Save"); $("tr:even").css('background-color', 'lightGrey'); $("tr:odd").css("background-color", "Pink"); } }, error: function () { alert('get error !!'); } }); } function Search() { $.ajax({ url: 'Employee.aspx/Search', type: 'post', contentType: 'application/json;charset=utf-8', dataType: 'json', data: "{A: '" + $("#ddlsearch").val() + "',B: '" + $("#txtsearch").val() + "'}", success: function (_dt) { _dt = JSON.parse(_dt.d); $("#tbl").find("tr:gt(0)").remove(); if (_dt != "") { for (var i = 0; i < _dt.length; i++) { $("#tbl").append('<tr><td>' + _dt[i].ContactPerson + '</td> , <td>' + _dt[i].Bname + '</td> <td>' + _dt[i].address + '</td> <td>' + _dt[i].Email + '</td> <td>' + _dt[i].Sname + '</td> <td>' + (_dt[i].vender == "1 " ? "yes" : "NO") + '</td> <td>' + (_dt[i].hub == "1" ? "yes" : "No") + '</td> <td>' + (_dt[i].active == "1" ? "yes" : "no") + '</td> <td>' + _dt[i].cname + '</td> <td>' + _dt[i].pincode + '</td> <td>' + _dt[i].Zone + '</td> <td> <input type="button" id="btnedit" value="Edit" onclick="EditData(' + _dt[i].eid + ')" /> </td> <td> <input type="button" id="btndelete" value="Delete" onclick="DeleteData(' + _dt[i].eid + ')" /> </td> </tr>'); } } else { $("#tbl").find("tr").remove(); } }, error: function () { alert('Search error !!'); } }); } </script> </head> <body> <form id="form1" runat="server"> <div> <table><tr><td>Search:</td> <td><select id="ddlsearch"> <option value="0">--select--</option> <option value="1">City</option> <option value="2">Address</option> <option value="3">Bname</option> <option value="4">Email</option> </select> <input type="text" id="txtsearch" /> <input type="button" id="btnsearch" value="Search" onclick="Search()" /> </td> </tr></table> <table> <tr> <td>Branch Code:</td> <td> <input type="text" id="txtbcode" /> </td> <td>Contact Person:</td> <td> <input type="text" id="txtcperson" /></td> </tr> <tr> <td>Branch Name:</td> <td> <input type="text" id="txtbname" /> </td> <td>Email Id:</td> <td> <input type="text" id="txtemail" /></td> </tr> <tr> <td>Short Name:</td> <td> <input type="text" id="txtsname" /> </td> <td>Hub</td> <td> <input type="checkbox" id="chkhub" /></td> </tr> <tr> <td>Address:</td> <td> <input type="text" id="txtaddress" /> </td> <td>Vender:</td> <td> <input type="checkbox" id="chkvender" /></td> <td>Active:</td> <td> <input type="checkbox" id="chkactive" /></td> </tr> <tr> <td>country: </td> <td> <select id="ddlcountry"> <option>--select--</option> </select> </td> </tr> <tr> <td>City: </td> <td> <select id="ddlcity"> <option>--select--</option> </select> </td> </tr> <tr> <td>Pin Code:</td> <td> <input type="text" id="txtpin" /> </td> </tr> <tr> <td>Zone:</td> <td> <input type="text" id="txtzone" /></td> </tr> <tr> <td></td> <td> <input type="button" id="btnsave" value="Save" onclick="InsertData()" /></td> </tr> </table> <table id="tbl" border="1" > <tr > <th>ContactPerson</th> <th>Employee_Bname</th> <th>Address</th> <th>Email</th> <th>Sname</th> <th>Vender</th> <th>hub</th> <th>Active</th> <th>City</th> <th>Pincode</th> <th>Zone</th> </tr> </table> </div> </form> </body> </html>
Nitin ShakyaPosted Oct 3, 2018, 1:05 AM
Using System;using System.Collections.Generic;using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Web.Services; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace TestSagar1 { public partial class Employee : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static string Insert(string B, string C, string D, string E, int F, string G, int H, int I, int J, string K, string L,int M) { string _dt = ""; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("usp_emp_insert", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@idd", M); cmd.Parameters.AddWithValue("@ContactPerson", B); cmd.Parameters.AddWithValue("@Bname", C); cmd.Parameters.AddWithValue("@Email", D); cmd.Parameters.AddWithValue("@Sname", E); cmd.Parameters.AddWithValue("@hub", F); cmd.Parameters.AddWithValue("@address", G); cmd.Parameters.AddWithValue("@vender", H); cmd.Parameters.AddWithValue("@active", I); cmd.Parameters.AddWithValue("@city", J); cmd.Parameters.AddWithValue("@pincode", K); cmd.Parameters.AddWithValue("@Zone", L); SqlParameter pram = cmd.Parameters.Add("@bcode", SqlDbType.VarChar, 50); pram.Direction = ParameterDirection.Output; cmd.ExecuteNonQuery(); con.Close(); { _dt = cmd.Parameters["@bcode"].Value.ToString(); _dt = JsonConvert.SerializeObject(_dt); } return _dt; } [WebMethod] public static string City() { string _dt = ""; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("usp_city_get", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); con.Close(); if(ds.Tables[0].Rows.Count>0) { _dt = JsonConvert.SerializeObject(ds.Tables[0]); } return _dt; } [WebMethod] public static string Country() { string _dt = ""; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("usp_country_get", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); con.Close(); if (ds.Tables[0].Rows.Count > 0) { _dt = JsonConvert.SerializeObject(ds.Tables[0]); } return _dt; } [WebMethod] public static void Delete(int A) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("usp_emp_delete", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@eid", A); cmd.ExecuteNonQuery(); } [WebMethod] public static string Search(int A,string B) { string _dt = ""; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("usp_emp_search", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ddlsearch", A); cmd.Parameters.AddWithValue("@txtsearch", B); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); con.Close(); if (ds.Tables[0].Rows.Count > 0) { _dt = JsonConvert.SerializeObject(ds.Tables[0]); } return _dt; } [WebMethod] public static string Getdata() { string _dt = ""; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("usp_emp_select", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); con.Close(); if (ds.Tables[0].Rows.Count > 0) { _dt = JsonConvert.SerializeObject(ds.Tables[0]); } return _dt; } [WebMethod] public static string Edit(int A) { string _dt = ""; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("usp_emp_edit", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@eid", A); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); con.Close(); if (ds.Tables[0].Rows.Count > 0) { _dt = JsonConvert.SerializeObject(ds.Tables[0]); } return _dt; } } }
Ram kuttiPosted Jun 7, 2018, 4:45 AM
Very nice Easy to work
Reden RodriguezPosted May 3, 2018, 8:57 PM
It is not refreshing when I input a new data I need to press f5 just to see result can you tell how to make refresh method for this where to put it? I'm really new in mvc jquery
Aman VermaPosted Feb 25, 2018, 7:32 AM
******class File To Insert***** #region InsertTree public int InsertTree() { int rowInserted = 0; string conString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString; SqlConnection conn = new SqlConnection(conString); SqlCommand cmd = new SqlCommand("usp_ManageTree_InsertTree", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@TreeName", TreeName); cmd.Parameters.AddWithValue("@Price", Price); cmd.Parameters.AddWithValue("@TreeImage", TreeImage); try { conn.Open(); rowInserted = cmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { conn.Close(); } return rowInserted; } #endregion
shervin salimianPosted Dec 20, 2017, 8:47 AM
Can we use this example for uploading files in mvc by stored procedure?
shervin salimianPosted Dec 20, 2017, 8:45 AM
Hi thank you very much i like it
L APosted Oct 29, 2017, 5:44 PM
A great article for newbie's to mid-level developers. Thanks for sharing.
bishoe nbPosted Oct 27, 2017, 11:22 PM
Thank you.........................
sara zobeadiPosted Oct 12, 2017, 11:55 AM
Tnx about your grate article. I have a problem with fileuploder Edit Event And Show image . could you tell me what can i do plz?
Hamid KhanPosted Sep 29, 2017, 9:51 AM
Nice..............
DotNet coaderPosted Sep 4, 2017, 9:14 AM
Really this is an excellent article.keep sharing.....
Sanjith ZhaaPosted Jul 31, 2017, 6:06 AM
How to display three grid view tables?
DDhruv PatadiaPosted Jun 28, 2017, 10:02 AM
Already stored data of table only shows in table when i enter a new record ..how to display all records before adding new ?
Trường NguyễnPosted Apr 23, 2017, 1:55 PM
I got an error GET http://localhost:53684/admin/employee/EmployeeList 500 (Internal Server Error). Please tell me why?
jana kPosted Apr 18, 2017, 10:44 AM
Here I am getting invalid token error, please hep meHtml += '<td><a href="#" onclick="return getbyID(' + item.EmployeeID + ')">Edit</a> | <a href="#" onclick="Delele(' + item.EmployeeID + ')">Delete</a></td>';
jana kPosted Apr 18, 2017, 10:43 AM
Here I am getting Invalid or unexpected token error
jana kPosted Apr 18, 2017, 10:42 AM
Html += '<td><a href="#" onclick="return getbyID(' + item.EmployeeID + ')">Edit</a> | <a href="#" onclick="Delele(' + item.EmployeeID + ')">Delete</a></td>';
francia0604 francia0604Posted Apr 18, 2017, 9:22 AM
Thank you very much for the contribution. It was great help
Aashish KalaPosted Mar 29, 2017, 7:44 AM
Thank you so much anoop sir really nice article
arun kumarPosted Feb 1, 2017, 9:20 AM
Thanks Anoop for wonderful article.How can i add a dropdown list in the add and edit form. where i need to call load function in jquery.
Sarvesh GujratiPosted Jan 18, 2017, 5:50 AM
Thnks Anoop ,Excellent, The problem i am getting with my code is that the list is returning correct data but in front end state and country is coming undefined . Could you please correct me on that where i am wrong ?
Manav PandyaPosted Dec 21, 2016, 2:44 AM
Error comes when try to add an employee Anoop Kumar Sharma
Antony ClintonPosted Nov 1, 2016, 9:39 AM
When i press the Add NEw Employee button nothing is happening. Please do help
Eshant KapoorPosted Oct 5, 2016, 1:13 AM
Thanks for sharing..can you please share it with paging in grid
ciotti ciottiPosted Sep 30, 2016, 10:37 AM
It is possible to add the datatable? "https://www.datatables.net/"
Delpin Susai RajPosted Aug 28, 2016, 10:57 AM
Good one
Vivek KumarPosted Aug 23, 2016, 3:51 PM
Nice one
Pete SchieckPosted Aug 17, 2016, 11:06 AM
You have an EXCELLENT grasp of writing as well as coding! Thanks, so much, for helping me finally understand the integration of Ajax into MVC.
Ravi KandelPosted Jul 14, 2016, 11:58 AM
Thanks for sharing.
Gowtham KPosted Jul 13, 2016, 12:55 PM
Good One, Thanks for sharing:)
sreenivasa kPosted Jul 13, 2016, 12:50 PM
Nice one
Amol SarkatePosted Jul 13, 2016, 8:56 AM
Nice job
Debendra DashPosted Jul 13, 2016, 1:57 AM
Good one..
farooq smdPosted Jul 12, 2016, 1:41 PM
Nice
kalu singh raoPosted Jul 12, 2016, 1:45 AM
Nice...