jQuery AJAX: Check Record Exists or Not using C# VB.Net and WebMethod

Last Reply 24 days ago By dharmendr

Posted 24 days ago

Hello.

how to check data is exists or not in jquery ajax.. if data is not exists then asp.net Grid not show in web form..   

<script type="text/javascript">
    $(document).ready(function () {
        $("#txtFname").keyup(function () {
            var findName = $("#txtFname").val()
            //  var len = 0;
            len = findName.length;
            if (findName != "") {
                //    alert(findName);
                $.ajax({
                    method: "GET",
                    url: "../Jquery_Examples/save_Employee_Jquery.aspx?findName=" + findName,
                    success: function (data) {
                        $("#bindData").html(data);
                    }
                });
            }
        });
    });
</script>
<table style="width: 40%;">
    <tr>
        <td>
            First Name :
        </td>
        <td>
            <input type="text" id="txtFname" />
            &nbsp;&nbsp;
            <p id="lblMsg">
            </p>
        </td>
    </tr>
</table>
<div id="bindData">
</div>

----------- C# Code----------

private void Page_Load()
{
    //  check finddata is available or not in page load
    string findName = Request.QueryString["findName"].ToString();
    if (findName != null)
    {
        findData(findName);
    }

} // end of page load 

private void findData(string findName)
{
    try
    {
        conn = new SqlConnection(getConnection);
        conn.Open();
        string query = "select * from EmployeeData WHERE Fname LIKE  @findName + '%'";
        cmd = new SqlCommand(query, conn);
        cmd.Parameters.AddWithValue("@findName", findName);
        SqlDataReader reader = cmd.ExecuteReader();

        DataTable dt = new DataTable();
        dt.Load(reader);
        if (dt.Rows.Count > 0)
        {
            GrdEmployee.DataSource = dt;
            GrdEmployee.DataBind();

            GrdEmployee.Visible = true;
        }
        else
        {
            GrdEmployee.Visible = false;
        }
    }
    catch (Exception ex)
    {
    }
} // end of findData method

 

Posted 24 days ago Modified on 24 days ago

Hi RahurkarP,

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

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

Page1.aspx

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('[id*=txtFname]').on('change', function () {
            var findName = $(this).val();
            if (findName != "") {
                window.location.href = "Default.aspx?findName=" + findName;
            }
        });
    });
</script>
<table style="width: 40%;">
    <tr>
        <td>
            First Name :
        </td>
        <td>
            <input type="text" id="txtFname" />
        </td>
    </tr>
</table>

Default.aspx

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var name = window.location.search.split('=')[1];
        if (name != '') {
            $.ajax({
                type: "POST",
                url: "Default.aspx/IsExist",
                contentType: "application/json;charset=utf-8",
                data: '{findName:"' + name + '"}',
                dataType: "json",
                success: function (data) {
                    if (data.d == "NotExist") {
                        $('[id*=GrdEmployee]').hide();
                    }
                    else {
                        $('[id*=GrdEmployee]').show();
                    }
                },
                error: function (result) {
                    alert(result.responsetext);
                }
            });
        }
    });
</script>
<asp:GridView runat="server" ID="GrdEmployee" EmptyDataText="No record" />

Namespaces

C#

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

VB.Net

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

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Request.QueryString["findName"] != null)
        {
            findData(Request.QueryString["findName"].ToString());
        }
    }
}

private void findData(string findName)
{
    try
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ConnectionString);
        conn.Open();
        string query = "select FirstName,LastName,City,Country from Employees WHERE FirstName LIKE  @findName + '%'";
        SqlCommand cmd = new SqlCommand(query, conn);
        cmd.Parameters.AddWithValue("@findName", findName);
        SqlDataReader reader = cmd.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(reader);
        GrdEmployee.DataSource = dt;
        GrdEmployee.DataBind();
    }
    catch (Exception ex)
    {
    }
}

[WebMethod]
public static string IsExist(string findName)
{
    string isRecordExist = "";
    try
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ConnectionString);
        conn.Open();
        string query = "select Count(*) from Employees WHERE FirstName LIKE @findName + '%'";
        SqlCommand cmd = new SqlCommand(query, conn);
        cmd.Parameters.AddWithValue("@findName", findName);
        int i = Convert.ToInt32(cmd.ExecuteScalar());
        isRecordExist = i > 0 ? "Exist" : "NotExist";
    }
    catch (Exception ex)
    {
    }
    return isRecordExist;
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then

        If Request.QueryString("findName") IsNot Nothing Then
            findData(Request.QueryString("findName").ToString())
        End If
    End If
End Sub

Private Sub findData(ByVal findName As String)
    Try
        Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings(1).ConnectionString)
        conn.Open()
        Dim query As String = "select FirstName,LastName,City,Country from Employees WHERE FirstName LIKE  @findName + '%'"
        Dim cmd As SqlCommand = New SqlCommand(query, conn)
        cmd.Parameters.AddWithValue("@findName", findName)
        Dim reader As SqlDataReader = cmd.ExecuteReader()
        Dim dt As DataTable = New DataTable()
        dt.Load(reader)
        GrdEmployee.DataSource = dt
        GrdEmployee.DataBind()
    Catch ex As Exception
    End Try
End Sub

<WebMethod()>
Public Shared Function IsExist(ByVal findName As String) As String
    Dim isRecordExist As String = ""
    Try
        Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings(1).ConnectionString)
        conn.Open()
        Dim query As String = "select Count(*) from Employees WHERE FirstName LIKE @findName + '%'"
        Dim cmd As SqlCommand = New SqlCommand(query, conn)
        cmd.Parameters.AddWithValue("@findName", findName)
        Dim i As Integer = Convert.ToInt32(cmd.ExecuteScalar())
        isRecordExist = If(i > 0, "Exist", "NotExist")
    Catch ex As Exception
    End Try
    Return isRecordExist
End Function

Screenshot