Call Server Side function from JavaScript on JavaScript Confirm Box Yes Button Click in ASP.Net

Last Reply 2 months ago By dharmendr

Posted 2 months ago

Hello Everyone,

I have a requirement from client that before the deleting the row from gridview they want an warning message that if we delete this records how many travelers will be affected as a popoup if they click yes it should go to delete button logic otherwise it should not go in to it if they press cancel

i have written my code below but getting some issue when i press ok on confirm function it is not going to button delete logic but when i press cancel it is saying in same page. 

Can anyone please help me on this issue? Thanks in Advance.

ALTER procedure [dbo].[sp_Deletesubunitwarning]
 @ID INT,
 @updatecount bigint output
as
BEGIN		
        BEGIN
            Select @updatecount = count(*)      
            from [dbo].[NewTravelerView] WHERE [SubUnitID]=@ID;

            insert into  dbo.travellog
            Select Travelerviewid,subunitid,getdate() ins_date    
            from [dbo].[NewTravelerView] WHERE [SubUnitID]=@ID;
        END 
	
--exec [dbo].[sp_Deleteandassignsubunitidvalueintraveler]  4

end
GO

 

[System.Web.Services.WebMethod]
public static string GetSubUnitDeleteWarningByID(string subunitId)
{
    var CnAltCai = safeGetAppconnstring();
    SqlConnection conn;
    conn = new SqlConnection(CnAltCai);
    SqlCommand cmd1 = new SqlCommand("sp_Deletesubunitwarning", conn);
    conn.Open();
    cmd1.CommandType = CommandType.StoredProcedure;
    cmd1.Parameters.AddWithValue("@ID", subunitId);
    cmd1.Parameters.Add("@updatecount", SqlDbType.BigInt);
    cmd1.Parameters["@updatecount"].Direction = ParameterDirection.Output;
    cmd1.ExecuteNonQuery();
    int updatecount = Convert.ToInt32(cmd1.Parameters["@updatecount"].Value.ToString());
    // int sumupdatecount = Convert.ToInt32(cmd2.Parameters["@sumupdatecount"].Value.ToString());
    conn.Close();
    return updatecount.ToString();
}

 

<script type="text/javascript">
    function SubUnitDeleteErrorWarning_SelectedItem(lnk) {
        var row = lnk.parentNode.parentNode;
        var rowIndex = row.rowIndex - 1;
        var subunitId = row.cells[1].innerHTML;
        PageMethods.GetSubUnitDeleteWarningByID(subunitId, onSuccess, onError);
        function onSuccess(result) {
            alert(result);
            // var data = JSON.parse(result);
            if (result > 0) {
                return confirm("Do you want to delete this subunit  so " + result + " travelers will be affected do you want to continue still?");
            }
            else {
                alert("No Travelers will be affected if you delete this subunit.")
                return false;
            }
        }
        function onError(err) {
            alert(err);
        }
    }
</script>
<asp:TemplateField HeaderText="Select">
    <itemtemplate>  
        <asp:LinkButton ID="btnDelete" Text="Delete"  CommandArgument='<%#Eval("ID")%>' CommandName="rowDelete" runat="server" OnClientClick ="if(!SubUnitDeleteErrorWarning_SelectedItem(this)) return false;"/> 
    </itemtemplate>
</asp:TemplateField>

 

You are viewing reply posted by: dharmendr 2 months ago.
Posted 2 months ago Modified on 2 months ago

Hi srihitha,

Check this example. Now please take its reference and correct your code.

Database

I have made use of the 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

<asp:ScriptManager runat="server" EnablePageMethods="true" />
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField HeaderText="Select">
            <ItemTemplate>
                <asp:LinkButton ID="btnDelete" Text="Delete" CommandArgument='<%#Eval("CustomerId")%>'
                    CommandName="rowDelete" runat="server" OnClientClick="if(!SubUnitDeleteErrorWarning_SelectedItem(this)) return false;" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="CustomerId" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>
<script type="text/javascript">
    function SubUnitDeleteErrorWarning_SelectedItem(lnk) {
        var row = lnk.parentNode.parentNode;
        var rowIndex = row.rowIndex - 1;
        var country = row.cells[3].innerHTML;
        PageMethods.GetSubUnitDeleteWarningByID(country, onSuccess, onError);
        function onSuccess(result) {
            if (result > 0) {
                if (confirm("Do you want to delete this subunit so " + result + " travelers will be affected do you want to continue still?")) {
                    PageMethods.DeleteSubUnitByID(country, function () {
                        alert(result + " Travelers deleted.");
                        window.location.reload();
                    }, onError);
                }
            }
            else {
                alert("No Travelers will be affected if you delete this subunit.")
                return false;
            }
        }
        function onError(err) {
            alert(err);
        }
    }
</script>

Namespaces

C#

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

VB.Net

Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        GridView1.DataSource = GetData();
        GridView1.DataBind();
    }
}

private static DataTable GetData()
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT * FROM Customers";
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);
                return dt;
            }
        }
    }
}

[WebMethod]
public static string GetSubUnitDeleteWarningByID(string country)
{
    return GetData().Select("Country='" + country + "'").Length.ToString();
}

[WebMethod]
public static string DeleteSubUnitByID(string country)
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "DELETE FROM Customers WHERE Country = @Country";
    SqlConnection con = new SqlConnection(conString);
    SqlCommand cmd = new SqlCommand(query, con);
    cmd.Parameters.AddWithValue("@Country", country);
    con.Open();
    int count = cmd.ExecuteNonQuery();
    con.Close();
    return count > 0 ? "1" : "0";
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        GridView1.DataSource = GetData()
        GridView1.DataBind()
    End If
End Sub

Private Shared Function GetData() As DataTable
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT * FROM Customers"
    Dim cmd As SqlCommand = New SqlCommand(query)
    Using con As SqlConnection = New SqlConnection(conString)
        Using sda As SqlDataAdapter = New SqlDataAdapter()
            cmd.Connection = con
            sda.SelectCommand = cmd
            Using dt As DataTable = New DataTable()
                sda.Fill(dt)
                Return dt
            End Using
        End Using
    End Using
End Function

<WebMethod()>
Public Shared Function GetSubUnitDeleteWarningByID(ByVal country As String) As String
    Return GetData().Select("Country='" & country & "'").Length.ToString()
End Function

<WebMethod()>
Public Shared Function DeleteSubUnitByID(ByVal country As String) As String
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "DELETE FROM Customers WHERE Country = @Country"
    Dim con As SqlConnection = New SqlConnection(conString)
    Dim cmd As SqlCommand = New SqlCommand(query, con)
    cmd.Parameters.AddWithValue("@Country", country)
    con.Open()
    Dim count As Integer = cmd.ExecuteNonQuery()
    con.Close()
    Return If(count > 0, "1", "0")
End Function

Screenshot