user829174 user829174 - 3 years ago 232
Ajax Question

JQuery UI autocomplete using AJAX and ASP.NET WebService

Implementing JQuery autocomplete using AJAX

I am having difficulties to make this program work.
what i'm trying to do is implementing autocomplete using JQuery UI API and getting the result from AJAX Enabled WCF service.

I believe that my problem is reaching the Web Service (if I implement it as asmx instead of svc it seems to be working)

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>


EDIT:
Console says:


"POST http://XXXXXX:7070/~/CostService.svc/GetAllPredictions 404 (Not Found) "


how can I reach it?

mo. mo.
Answer Source

make it RESTful!

but first split your service in a contract (interface) and an implementation (class).

then add this to your GetAllPredictions-Method

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

this makes it RESTful

add the webHttp enpointPoint-Behaviour.

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

then try to call it:

$(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
        });
    });

you may need to remove this lines:

    <Services>
        <asp:ServiceReference Path="CostService.svc" />
    </Services>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download