簡體   English   中英

jQuery自動完成+ Asp.net / C#/ SQL無法正常工作

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

不知道這是否是“太多的工作部件”類型的情況,但是我搜索了上下限的凈值,無法解決我的問題。

現在我要指出的是,嘗試“自動完成”的我的文本框嘗試但給出了錯誤消息(但是,當代碼在“測試應用程序”中單獨運行時,它可以正常工作),但是錯誤消息應該顯示為“錯誤”,所以我想知道這里的你們/加爾斯是否能夠提供幫助。

在學習Jquery / SQL / Asp.net的良好學習/培訓站點上的建議也將有很大幫助...

我確實嘗試過使用AJAX自動完成功能,但是無法正常工作,因此切換到了JQuery(不確定這是否是個好主意),因此可以在下面找到我的代碼:

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>

背后的代碼:

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配置

`<?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>`  

只需更改腳本標簽

url: "Default.aspx/GetAutoCompleteData", 

替換為:

url: "Webform2.aspx/GetAutoCompleteData",

參考: Link1

我建議您嘗試使用firefox附帶的Web開發人員工具,並檢查“網絡”標簽以查看是否獲得了預期的結果。 您可以通過以下鏈接獲取有關此信息的更多信息。 網絡監控器

由於AjaxControlToolkit現在已經過時了,因此您決定切換到jQuery確實很好。 有很多適合學習jQuery的好網站,這里有一些開始。 jQuery學習中心 W3C jQuery | Codecademy網站

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM