Uncheck selected ASP.Net GridView CheckBox if Error occurs using jQuery AJAX

Last Reply 2 months ago By dharmendr

Posted 2 months ago

I have a checkbox control on a vb.net webform that is used to indicate if a row should be marked for processing. The checkbox should not show "checked" unless all the validation rules are met.

Currently, I use a webmethod to call a SQL stored procedure that uses a RAISERROR to break the funciton with an error message if the validation rules are not met. 

The problem is that when I check the checkbox and call jquery webmethod, the checkbox remains checked even if a RAISERROR is called from my stored procedure.

I do not want to bind the data or refresh the page. I want to use javascript to prevent the checkbox from remaining checked if a RAISERROR event occurs.

ASP: 

<asp:TemplateField HeaderText="11. Mark" HeaderStyle-Wrap="false" SortExpression="Marked">
    <ItemTemplate>
        <asp:Checkbox ID="btnMark" runat="server" Checked='<%# Eval("Marked") %>' CssClass="form-check-input Mark"/>
    </ItemTemplate>
</asp:TemplateField>

Jquery:

        <%-- Update trust "Mark" checkbox --%>
        $(function () {
            $('.Mark').on('change', function () {
                var id = $(this).closest('tr').find('td').eq(0).html();
                var Marked = $(this).closest('tr').find('[id*=btnMark]:checked').val()
                var LabelFullname = document.getElementById('<%=LabelFullname.ClientID%>').innerText;

                $.ajax({
                    type: "POST",
                    url: "MOGP_Application.aspx/Mark",
                    data: "{id:" + id + ",Marked:'" + Marked + "', LabelFullname:'" + LabelFullname + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert("get session failed " + errorThrown);
                    }
                });

                $(this).closest('tr').find('[id*=btnMark]:checked').prop('checked', false)

            });
        });

 

    <WebMethod()>
    Public Shared Sub Mark(ByVal id As Integer, ByVal Marked As String, ByVal LabelFullname As String)
        Dim cmd As New SqlCommand("usp_Trust")
        Dim Action As String = ""
        If (Marked = "on") Then
            Action = "MARK"
        Else
            Action = "UNMARK"
        End If
        cmd.Parameters.AddWithValue("@Action", Action)
        cmd.Parameters.AddWithValue("@User", LabelFullname)
        cmd.Parameters.AddWithValue("@Parameter2", id)
        Dim conString As String = ConfigurationManager.ConnectionStrings("mogp_app").ConnectionString
        Using con As New SqlConnection(conString)
            cmd.Connection = con
            cmd.CommandTimeout = 300
            cmd.CommandType = CommandType.StoredProcedure
            Try
                Using sda As New SqlDataAdapter()
                    sda.SelectCommand = cmd
                    Using dt As New DataTable()
                        sda.Fill(dt)
                    End Using
                End Using
            Catch sqlresponse As SqlException
                Dim raiserror As SqlError
                For Each raiserror In sqlresponse.Errors
                    MsgBox(raiserror.Message)
                Next
            End Try
        End Using
    End Sub

 

Posted 2 months ago

Hi Warren,

To prevent CheckBox from remaining checked if RAISERROR event occurs you need to change the return type to string or int or as per any other type and and return the value based on the return type.

Then in the ajax success function based on the return value uncheck the checkbox.

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

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('.Mark').on('change', function () {
            var id = $(this).closest('tr').find('td').eq(0).html();
            var checkbox = $(this).closest('tr').find('[id*=btnMark]');
            var Marked = $(this).closest('tr').find('[id*=btnMark]:checked').val()
            var LabelFullname = document.getElementById('<%=LabelFullname.ClientID%>').innerText;

            $.ajax({
                type: "POST",
                url: "Default.aspx/Mark",
                data: "{id:" + id + ",Marked:'" + Marked + "', LabelFullname:'" + LabelFullname + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("get session failed " + errorThrown);
                },
                success: function (response) {
                    if (response.d == "failed") {
                        $(checkbox).prop('checked', false)
                    }
                }
            });
        });
    });
</script>
<asp:Label ID="LabelFullname" runat="server" Text="Test" />
<asp:GridView runat="server" ID="gvtfaLoan" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="0. ID" ShowHeader="false" HeaderStyle-Wrap="false"
            SortExpression="ID" />
        <asp:TemplateField HeaderText="11. Mark" HeaderStyle-Wrap="false" SortExpression="Marked">
            <ItemTemplate>
                <asp:CheckBox ID="btnMark" runat="server" Checked='<%# Eval("Marked") %>' CssClass="form-check-input Mark" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        System.Data.DataTable dt = new System.Data.DataTable();
        dt.Columns.AddRange(new System.Data.DataColumn[] { 
            new System.Data.DataColumn("ID", typeof(int)), 
            new System.Data.DataColumn("Marked", typeof(bool)) });
        dt.Rows.Add(1, false);
        dt.Rows.Add(2, false);
        gvtfaLoan.DataSource = dt;
        gvtfaLoan.DataBind();
    }
}

[System.Web.Services.WebMethod]
public static string Mark(int id, string Marked, string LabelFullname)
{
    try
    {
        int age = int.Parse("test");
        return "success";
    }
    catch (Exception ex)
    {
        return "failed";
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As Data.DataTable = New Data.DataTable()
        dt.Columns.AddRange(New Data.DataColumn() {
                            New Data.DataColumn("ID", GetType(Integer)),
                            New Data.DataColumn("Marked", GetType(Boolean))})
        dt.Rows.Add(1, False)
        dt.Rows.Add(2, False)
        gvtfaLoan.DataSource = dt
        gvtfaLoan.DataBind()
    End If
End Sub

<Services.WebMethod()>
Public Shared Function Mark(ByVal id As Integer, ByVal Marked As String, ByVal LabelFullname As String) As String
    Try
        Dim age As Integer = Integer.Parse("test")
        Return "success"
    Catch ex As Exception
        Return "failed"
    End Try
End Function

Screenshot