简体   繁体   中英

Jquery Auto Complete + Asp.net / c# / SQL not working

Not sure if this is a 'too many working parts' type situation but I have searched the net high and low and cant solve my issue.

I've got to a point now that it my text box that attempts to 'auto complete' tries but gives an error message (However when the code is ran separately in 'test application' it works fine) however the error message should says 'Error', so I wondered if you guys / gals here maybe able to help.

Also suggestions on good learning / training sites to learn Jquery / SQL / Asp.net would be a great help...

I did try using AJAX auto complete but it failed to work so switched to JQuery (not sure if this was a good idea or not) so my code can be found below:

Webform2.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="SicknessDBNewSite.WebForm2" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">




<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>  
    <script type="text/javascript">
        $(document).ready(function () {
            SearchText();
        });
        function SearchText() {
            $(".autosuggest").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "Default.aspx/GetAutoCompleteData",
                        data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
                        dataType: "json",
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (result) {
                            alert("Error");
                        }
                    });
                }
            });
        }
    </script>

    <title></title>
    <style type="text/css">
        .style1
        {
            width: 72%;
        }
        .style2
        {
            width: 443px;
        }
        .style3
        {
            text-align: center;
            text-decoration: underline;
        }
        .style4
        {
            width: 443px;
            height: 65px;
        }
        .style5
        {
            height: 65px;
        }
        .style6
        {
            text-align: center;
        }
        .style7
        {
            width: 443px;
            height: 59px;
        }
        .style8
        {
            height: 59px;
        }
        #txtSearch
        {
            width: 500px;
        }
    </style>
</head>
<body>


    <form id="form1" runat="server">
    <div style="text-align: center">
        <h1 class="style3">
            Test Form Submission
        </h1>

        <table class="style1" align="center">
            <tr>
                <td class="style2">
                    Name</td>
                <td>

                    <input type="text" id="txtSearch" class="autosuggest" />

                </td>
            </tr>
            <tr>
                <td class="style2">
                    Grade</td>
                <td>
                    <asp:TextBox ID="txtgrade" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Depot</td>
                <td>
                    <asp:TextBox ID="txtdepot" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Nature of Illness?</td>
                <td>
                    <asp:TextBox ID="txtillness" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Appointment made to see doctor (Yes or No)?</td>
                <td>
                    <asp:RadioButton ID="RadioAppointmentYes" runat="server" Text="Yes" GroupName="Appointment" />
                    <asp:RadioButton ID="RadioAppointmentNo" runat="server" Text="No" GroupName="Appointment" />
                    <asp:TextBox ID="txtAppointment" runat="server" Visible="False"></asp:TextBox>
</td>
            </tr>
            <tr>
                <td class="style2">
                    Medication Taken (Yes or No)?</td>
                <td class="style6">
                    <asp:RadioButton ID="RadioMedicationYes" runat="server" Text="Yes" GroupName="Medication" />
                    <asp:RadioButton ID="RadioMedicationNo" runat="server" Text="No" GroupName="Medication" />
                    <asp:TextBox ID="txtMedication" runat="server" Visible="False"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Expected length of absence?</td>
                <td>
                    <asp:TextBox ID="txtabsence" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    If not contacted by staff member, who contacted on their behalf?</td>
                <td>
                    <asp:TextBox ID="txtcontactby" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Likely resumption date?</td>
                <td>
                    <asp:TextBox ID="txtresumedate" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Contact telephone number</td>
                <td>
                    <asp:TextBox ID="txtcontactnum" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Latest update date</td>
                <td>
                    <asp:TextBox ID="txtupdate" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style4">
                    Details</td>
                <td class="style5">
                    <asp:TextBox ID="txtdetails" TextMode="MultiLine" runat="server" Width="500px" 
                        Height="50px" style="text-align: right"></asp:TextBox>
                    </td>
            </tr>
            <tr>
                <td class="style2">
                    Resumption Date</td>
                <td>
                    <asp:TextBox ID="txtresumeddate" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style7">
                    Detail</td>
                <td class="style8">
                    <asp:TextBox ID="txtdetail" TextMode="MultiLine" runat="server" Width="500px" Height="50px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Is the person still on medication at the time of resumption?</td>
                <td>
                    <asp:TextBox ID="txtmedonreturn" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Controller / Planner&#39;s name</td>
                <td>
                    <asp:TextBox ID="txtreporter" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Date of contact</td>
                <td>
                    <asp:TextBox ID="txtdateofcontact" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Date and time of next shift</td>
                <td>
                    <asp:TextBox ID="txtdatetimeshift" runat="server" Width="500px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" Width="100px" />
                </td>
            </tr>
            </table>
                </div>
    <a href="http://skynet/webform1.aspx">
     <asp:Label ID="Label1" runat="server" ForeColor="Green" Visible="False" /></asp:Label>
     </a>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionStringTestFormSubmission %>" 

        SelectCommand="SELECT id, Name, Grade, Depot FROM Crewnames WHERE Name LIKE %da%"></asp:SqlDataSource>
    <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
        ConnectionString="<%$ ConnectionStrings:CrewNameString %>" 
        SelectCommand="SELECT * FROM [Crewnames]"></asp:SqlDataSource>
    </form>
</body>
</html>

Code Behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using System.Web.Script.Services;

namespace SicknessDBNewSite
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringTestFormSubmission"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            con.Open();
            txtdateofcontact.Text = DateTime.Now.ToShortDateString();
            txtresumedate.Text = DateTime.Today.AddDays(+1).ToShortDateString();
        }

        [WebMethod]

        public static List<string> GetAutoCompleteData(string username)
        {
            List<string> result = new List<string>();
            using (SqlConnection con = new SqlConnection("Data Source=G00069-PC\\SQLEXPRESS;Initial Catalog=SicknessDatabase;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD"))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM [Crewnames] WHERE Name LIKE '%'+@SearchText+'%'", con))
                {
                    con.Open();
                    cmd.Parameters.AddWithValue("@SearchText", username);
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        result.Add(dr["Name"].ToString());
                    }
                    return result;
                }
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {

            if (RadioAppointmentYes.Checked)
            {
                txtAppointment.Text = "Yes";
            }
            else if (RadioAppointmentNo.Checked)
            {
                txtAppointment.Text = "No";
            }

            if (RadioMedicationYes.Checked)
            {
                txtMedication.Text = "Yes";
            }
            else if (RadioMedicationNo.Checked)
            {
                txtMedication.Text = "No";
            }
            SqlCommand cmd = new SqlCommand("insert into sicknesstest values('"+txtname.Text+"','"+txtgrade.Text+"','"+txtdepot.Text+"','"+txtillness.Text+"','"+txtAppointment.Text+"','"+txtMedication.Text+"','"+txtabsence.Text+"','"+txtcontactby.Text+"','"+txtupdate.Text+"','"+txtdetails.Text+"','"+txtresumedate.Text+"','"+txtdetail.Text+"','"+txtmedonreturn.Text+"','"+txtreporter.Text+"','"+txtdateofcontact.Text+"','"+txtresumeddate.Text+"')", con);
            cmd.ExecuteNonQuery();
            con.Close();
            Label1.Visible = true;
            Label1.Text = "Your Data has been stored successfully! Click here to view";
            txtname.Text = "";
            txtgrade.Text = "";
            RadioAppointmentYes.Checked = false;
            RadioAppointmentNo.Checked = false;
            RadioMedicationYes.Checked = false;
            RadioMedicationNo.Checked = false;
            txtAppointment.Text = "";
            txtMedication.Text = "";
            txtdepot.Text = "";
            txtillness.Text = "";
            txtabsence.Text = "";
            txtcontactnum.Text = "";
            txtcontactby.Text = "";
            txtupdate.Text = "";
            txtdetails.Text = "";
            txtresumedate.Text = "";
            txtdetail.Text = "";
            txtmedonreturn.Text = "";
            txtreporter.Text = "";
            txtdateofcontact.Text = "";
            txtresumeddate.Text = "";
            txtdatetimeshift.Text = "";
        }


    }

}       

` Web Config

`<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>


  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="SicknessDatabaseConnectionString" connectionString="Data Source=G00069-PC\sqlexpress;Initial Catalog=SicknessDatabase;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD"
      providerName="System.Data.SqlClient" />
    <add name="ConnectionStringTestFormSubmission" connectionString="Data Source=G00069-PC\SQLEXPRESS;Initial Catalog=SicknessDatabase;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD"
      providerName="System.Data.SqlClient" />
    <add name="ProductionConnectionStringNames" connectionString="Data Source=saturn\gbrfdev;Initial Catalog=Production;Integrated Security=True"
      providerName="System.Data.SqlClient" />
    <add name="ProductionEntitiesNames" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=saturn\gbrfdev;initial catalog=Production;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;"

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>
    <membership>
      <providers>
        <clear />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="false">
      <providers>
        <clear />
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>
    <pages>
        <controls>
        <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
      </controls>
    </pages>
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
</configuration>`  

Just change in the script tag

url: "Default.aspx/GetAutoCompleteData", 

Replace by :

url: "Webform2.aspx/GetAutoCompleteData",

reference : Link1

I would suggest you to try web developer tools that come with firefox and check the Network tab to see if you are getting the expected results. You can get more information about this from following link. Network Monitor

Your decision to switch into jQuery is really good as AjaxControlToolkit is now becoming obsolete. There are plenty of good sites for leaning jQuery and here a few to start with. jQuery Learning Center W3C jQuery | Codecademy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM