繁体   English   中英

使用AJAX和ASP.NET WebService的JQuery UI自动完成

[英]JQuery UI autocomplete using AJAX and ASP.NET WebService

使用AJAX实现JQuery自动完成

我很难使该程序正常工作。 我想做的是使用JQuery UI API实现自动完成功能,并从启用AJAX的WCF服务获取结果。

我相信我的问题正在到达Web服务(如果我将其实现为asmx而不是svc,则似乎可以正常工作)

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="SandwichServices._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
    <link href="Styles/jquery-ui-1.8.21.custom.css" rel="stylesheet" type="text/css" />
    <script language="javascript" type="text/javascript">
// <![CDATA[
        $(document).ready(function () {
            $(".searchinput").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "~/CostService.svc/GetAllPredictions",
                        data: "{'keywordStartsWith':'" + request.term + "'}",
                        dataType: "json",
                        async: true,
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (result) {
                            alert("Due to unexpected errors we were unable to load data");
                        }
                    });
                },
                minLength: 2
            });
        });

// ]]>
    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="CostService.svc" />
        </Services>
    </asp:ScriptManager>
    <div class="ui-widget">
        <asp:Label ID="lblSearch" Text="Search" AssociatedControlID="txbSearchKeyword" runat="server"></asp:Label>
        <asp:TextBox ID="txbSearchKeyword" runat="server" CssClass="searchinput"></asp:TextBox>
        <asp:Button ID="Button2" Text="Go!" runat="server" OnClick="Search_Click" />
    </div>
    <asp:Literal ID="litStatus" runat="server"></asp:Literal>
</asp:Content>

Default.aspx.cs

using System;

namespace SandwichServices
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Search_Click(object sender, EventArgs e)
        {
            litStatus.Text = "Search conducted for keyword: " + txbSearchKeyword.Text;
        }
    }
}

CostService.svc.cs

using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SandwichServices
{
    [ServiceContract(Namespace = "SandwichServices")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CostService
    {
        private readonly List<string> _names = new List<string> // dummy list
                                         {
                                             "one",
                                             "one111",
                                             "one2222",
                                             "one4444",
                                         };

        [OperationContract]
        public IList<string> GetAllPredictions(string keywordStartsWith)
        {
            IList<string> output = (from c in _names
                                    where c.Contains(keywordStartsWith)
                                    select c).ToList();
            return output;
        }
    }
}

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" />
  </connectionStrings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />

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

  </system.web>

  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="SandwichServices.CostServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <services>
      <service name="SandwichServices.CostService">
        <endpoint address="" behaviorConfiguration="SandwichServices.CostServiceAspNetAjaxBehavior"
          binding="webHttpBinding" contract="SandwichServices.CostService" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

编辑:控制台说:

“ POST http:// XXXXXX:7070 /〜/ CostService.svc / GetAllPredictions 404(未找到)”

我如何到达?

使它变得RESTful!

但首先将您的服务分为合同(接口)和实现(类)。

然后将其添加到您的GetAllPredictions-Method

[WebInvoke(Method = "POST", 
                    ResponseFormat = WebMessageFormat.Json, 
                    UriTemplate = "predictions/{keywordStartsWith}")]

这使其变得RESTful

添加webHttp enpointPoint-Behaviour。

<behavior name="SandwichServices.CostServiceAspNetAjaxBehavior">
    <webHttp />
    <enableWebScript />
</behavior>

然后尝试调用它:

$(document).ready(function () {
        $(".searchinput").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/predictions/" + request.term,
                    async: true,
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Due to unexpected errors we were unable to load data");
                    }
                });
            },
            minLength: 2
        });
    });

您可能需要删除以下行:

    <Services>
        <asp:ServiceReference Path="CostService.svc" />
    </Services>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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