0

AJAXを使用したJQueryオートコンプリートの実装

このプログラムを機能させるのに苦労しています。私がやろうとしているのは、JQuery UI APIを使用してオートコンプリートを実装し、AJAX対応のWCFサービスから結果を取得することです。

私の問題はWebサービスに到達していると思います(svcではなくasmxとして実装すると、機能しているようです)

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(見つかりません)"

どうすれば到達できますか?

4

1 に答える 1

1

それをRESTfulにしてください!

ただし、最初にサービスをコントラクト(インターフェース)と実装(クラス)に分割します。

次に、これをGetAllPredictions-Methodに追加します

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

これによりRESTfulになります

webHttpenpointPoint-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>
于 2012-07-06T14:28:25.600 に答える