Hi lingers,
Make Ajax call to web method on view button click.
Check this example. Now please take its reference and correct your code.
HTML
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
Status:
<asp:Label ID="NameL" runat="server" />
<br />
<asp:HiddenField ID="hfCheckedIds" runat="server" />
<asp:HiddenField ID="hfId" runat="server" />
Page Size:
<asp:DropDownList runat="server" ID="ddlPageSize">
<asp:ListItem Text="1" Value="1" />
<asp:ListItem Text="2" Value="2" Selected="True" />
<asp:ListItem Text="10" Value="10" />
</asp:DropDownList>
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID" Width="100%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CustomerID" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="First Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button CssClass="view" Text="Unuseable" ID="Inkview" runat="server" ForeColor="white" BackColor="#FF6600" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div class="Pager" style="width: 100%"></div>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm.add_endRequest(function (sender, e) {
if (sender._postBackSettings.panelsToUpdate != null) {
GetCustomers(1);
}
});
};
</script>
<script type="text/javascript" src=" https://code.jquery.com/jquery-3.5.1.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="ASPSnippets_Pager.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
GetCustomers(parseInt(1));
var checked = [];
$('[id*=chkSelect]').on('click', function () {
if ($(this).is(":checked")) {
checked.push($(this).closest('tr').find('td').eq(1).html());
} else {
checked.pop($(this).closest('tr').find('td').eq(1).html());
}
$('[id*=hfCheckedIds]').val(checked.join(','));
});
});
$(document).on("click", '.Pager .page', function () {
GetCustomers(parseInt($(this).attr('page')));
});
var term = '';
$(document).on("keyup", 'input[type=search]', function () {
term = $(this).val();
GetCustomers(parseInt(1));
});
$(document).on("change", '[id*=ddlPageSize]', function () {
GetCustomers(parseInt(1));
});
function SearchTerm() {
return jQuery.trim($("input[type=search]").val());
};
$(document).on('click', '.view', function () {
var id = $(this).closest('tr').find('td').eq(1).html();
$('[id*=hfId]').val(id);
$.ajax({
type: "POST",
url: "CS.aspx/UpdateCustomer",
data: '{empid: ' + id + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('[id*=NameL]').html(response.d);
GetCustomers(parseInt(1));
},
error: function (response) {
alert(response.responseText);
}
});
return false;
});
var i = 0;
function GetCustomers(pageIndex) {
$.ajax({
type: "POST",
url: "CS.aspx/GetCustomers",
data: '{searchTerm: "' + SearchTerm() + '", pageIndex: ' + pageIndex + ', pageSize: ' + $("[id*=ddlPageSize]").val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('[id$=gvCustomers]').prepend($("<thead></thead>").append($('[id$=gvCustomers]').find("tr:first"))).DataTable().destroy();
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Customers");
var row = $("[id$=gvCustomers] tbody tr:last-child").eq(0).clone(true);
$("[id$=gvCustomers] tbody tr").not($("[id$=gvCustomers] tbody tr:first-child")).remove();
$.each(customers, function () {
$("td", row).eq(1).html($(this).find("CustomerId").text());
$("td", row).eq(2).html($(this).find("Name").text());
$("td", row).eq(3).html($(this).find("Country").text());
$("[id$=gvCustomers]").append(row);
row = $("[id$=gvCustomers] tbody tr:last-child").eq(0).clone(true);
});
$("[id$=gvCustomers] tbody tr:first-child").remove();
if (i != 0) {
$('[id$=gvCustomers]').DataTable({
"paging": false,
"info": false
});
} else {
$('[id$=gvCustomers]')
.prepend($("<thead></thead>").append($('[id$=gvCustomers]').find("tr:first")))
.DataTable({
"paging": false,
"info": false
});
}
if (term != '') {
$('input[type=search]').val(term);
}
$('input[type=search]').focus();
i++;
var pager = xml.find("Pager");
$(".Pager").ASPSnippets_Pager({
ActiveCssClass: "current",
PagerCssClass: "pager",
PageIndex: parseInt(pager.find("PageIndex").text()),
PageSize: parseInt(pager.find("PageSize").text()),
RecordCount: parseInt(pager.find("RecordCount").text())
});
},
error: function (response) {
alert(response.responseText);
}
});
}
</script>
Namespaces
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDummyRow();
}
}
private void BindDummyRow()
{
DataTable dummy = new DataTable();
dummy.Columns.Add("CustomerID");
dummy.Columns.Add("Name");
dummy.Columns.Add("Country");
dummy.Rows.Add();
gvCustomers.DataSource = dummy;
gvCustomers.DataBind();
}
[WebMethod]
public static string GetCustomers(int pageIndex, string searchTerm, int pageSize)
{
string query = "[Customers_GetCustomersPageWise]";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SearchTerm", searchTerm);
cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
cmd.Parameters.AddWithValue("@PageSize", pageSize);
cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
return GetData(cmd, pageIndex, pageSize).GetXml();
}
[WebMethod]
public static string UpdateCustomer(int empid)
{
string status = "";
HttpContext.Current.Session["DatakeyValue"] = empid;
string updateSQL = "UPDATE Customers SET Country='' WHERE CustomerID='" + empid + "'";
SqlConnection dbConn = new SqlConnection();
dbConn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = dbConn;
cmd.CommandText = updateSQL;
cmd.CommandType = CommandType.Text;
try
{
dbConn.Open();
int updated = cmd.ExecuteNonQuery();
status = updated == 1 ? "working" : "Not working";
}
catch (Exception err)
{
}
finally
{
dbConn.Close();
}
return status;
}
private static DataSet GetData(SqlCommand cmd, int pageIndex, int pageSize)
{
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds, "Customers");
DataTable dt = new DataTable("Pager");
dt.Columns.Add("PageIndex");
dt.Columns.Add("PageSize");
dt.Columns.Add("RecordCount");
dt.Rows.Add();
dt.Rows[0]["PageIndex"] = pageIndex;
dt.Rows[0]["PageSize"] = pageSize;
dt.Rows[0]["RecordCount"] = cmd.Parameters["@RecordCount"].Value;
ds.Tables.Add(dt);
return ds;
}
}
}
}
Screenshot