Hi namojainashis...,
Check the below example.
Using the below article i have created the example.
Database
I have used following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
HTML
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
<tr>
<td>Name:<br />
<asp:TextBox ID="txtName" runat="server" />
</td>
<td>Country:<br />
<asp:TextBox ID="txtCountry" runat="server" />
</td>
<td>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
</td>
</tr>
</table>
<hr />
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound"
DataKeyNames="Id" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit" PageSize="3" AllowPaging="true" OnPageIndexChanging="OnPaging"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added."
Width="450">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("Country") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
Namespaces
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.PopulateGridView();
}
}
protected void Insert(object sender, EventArgs e)
{
string name = txtName.Text;
string country = txtCountry.Text;
txtName.Text = "";
txtCountry.Text = "";
string apiUrl = "http://localhost:26404/api/CustomerAPI";
object input = new
{
Name = name,
Country = country
};
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
string json = client.UploadString(apiUrl + "/UpdateCustomer", inputJson);
this.PopulateGridView();
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
this.PopulateGridView();
}
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
gvCustomers.PageIndex = e.NewPageIndex;
this.PopulateGridView();
}
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvCustomers.Rows[e.RowIndex];
int customerId = Convert.ToInt32(gvCustomers.DataKeys[e.RowIndex].Values[0]);
string name = (row.FindControl("txtName") as TextBox).Text;
string country = (row.FindControl("txtCountry") as TextBox).Text;
string apiUrl = "http://localhost:26404/api/CustomerAPI";
object input = new
{
Id= customerId,
Name = name,
Country = country
};
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
string json = client.UploadString(apiUrl + "/UpdateCustomer", inputJson);
gvCustomers.EditIndex = -1;
this.PopulateGridView();
}
protected void OnRowCancelingEdit(object sender, EventArgs e)
{
gvCustomers.EditIndex = -1;
this.PopulateGridView();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int customerId = Convert.ToInt32(gvCustomers.DataKeys[e.RowIndex].Values[0]);
string apiUrl = "http://localhost:26404/api/CustomerAPI";
object input = new
{
Id= customerId
};
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
string json = client.UploadString(apiUrl + "/DeleteCustomer", inputJson);
this.PopulateGridView();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != gvCustomers.EditIndex)
{
(e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
}
}
private void PopulateGridView()
{
string apiUrl = "http://localhost:26404/api/CustomerAPI";
object input = new
{
Name = txtName.Text.Trim(),
Country = txtCountry.Text.Trim()
};
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
string json = client.UploadString(apiUrl + "/GetCustomers", inputJson);
gvCustomers.DataSource = (new JavaScriptSerializer()).Deserialize<List<Customer>>(json);
gvCustomers.DataBind();
}
public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
WebAPI
Model
public class CustomerModel
{
/// <summary>
/// Gets or sets Id.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Gets or sets Name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets Country.
/// </summary>
public string Country { get; set; }
}
Namespaces
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Http;
Controller
public class CustomerAPIController : ApiController
{
[Route("api/CustomerAPI/GetCustomers")]
[HttpPost]
public List<Customer> GetCustomers(CustomerModel customer)
{
List<Customer> customers = new List<Customer>();
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT CustomerId,Name,Country FROM Customers WHERE (Name LIKE @Name + '%' OR @Name IS NULL) AND (Country = @Country OR @Country IS NULL)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", !string.IsNullOrEmpty(customer.Name) ? customer.Name : (object)DBNull.Value);
cmd.Parameters.AddWithValue("@Country", !string.IsNullOrEmpty(customer.Country) ? customer.Country : (object)DBNull.Value);
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new Customer
{
Id = sdr["CustomerId"].ToString(),
Name = sdr["Name"].ToString(),
Country = sdr["Country"].ToString()
});
}
}
con.Close();
}
}
return customers;
}
[Route("api/CustomerAPI/InsertCustomer")]
[HttpPost]
public void InsertCustomer(CustomerModel customer)
{
string query = "INSERT INTO Customers VALUES(@Name, @Country)";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@Name", customer.Name);
cmd.Parameters.AddWithValue("@Country", customer.Country);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
[Route("api/CustomerAPI/UpdateCustomer")]
[HttpPost]
public void UpdateCustomer(CustomerModel customer)
{
string query = "UPDATE Customers SET Name=@Name, Country=@Country WHERE CustomerId=@CustomerId";
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@CustomerId", customer.Id);
cmd.Parameters.AddWithValue("@Name", customer.Name);
cmd.Parameters.AddWithValue("@Country", customer.Country);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
[Route("api/CustomerAPI/DeleteCustomer")]
[HttpPost]
public void DeleteCustomer(CustomerModel customer)
{
string query = "DELETE FROM Customers WHERE CustomerId=@CustomerId";
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@CustomerId", customer.Id);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
}
Screenshot