使用C#和SQL Server数据库进行jQuery自动完成

时间:2012-01-23 21:34:21

标签: jquery asp.net ajax dynamic asp.net-3.5

我正在尝试在动态创建的文本框中使用jQuery自动完成功能。这是我第一次使用jQuery,所以我不太确定我要去哪里... 我的ASMX页面代码工作正常&生成结果,但我的javascript 自动完成不是完全调用页面(在调试中尝试)并且它没有给我错误 消息...请帮助!!

编辑:       我仍然有错误“ASP.NET Ajax客户端框架无法加载。”

<script src="/ScriptResource.axd?d=dRAn80ZulnXIbHUFZAi0thqEaFFdeMlwAh6uA_ciIINTs7jTUe13ADvaDyjOl6tPSr-1TN4Bqt6MFVjznyiXABGNxDhFk5_-02EGxOku0B-Tim4ebG59zhvC6DdsHV11uoIY024U1o0IMngrTBO45x9tPeG-PiyEUPEypUFf795T-3SY0&amp;t=ffffffffb868b5f4" type="text/javascript"></script>
<script type="text/javascript">
<!--
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.'); 

在文本框中输入后,我收到弹出错误:

Ajax错误:researcher_list.asmx / FetchResList:错误:未定义:内部服务器错误:500

已编辑代码:

Aspx代码:

$(function() {
    $('input:text').autocomplete({
        source: function(request, response) {
            var pString = '{ "resName": "' + request.term + '" }';
            $.ajax({
                url: "researcher_list.asmx/FetchResList", /* same root as the page? */
                data: pString,
                dataType: "jsond",
                type: "POST",
                contentType: "application/json", /* simplify */
                converters: {/* avoid the d or no d issue, works with 3.5 or prior this way */
                    "json jsond": function(msg) {
                        return msg.hasOwnProperty('d') ? msg.d : msg;
                    }
                },
                success: function(data) {/* assumes data always returned and it IS called item in the JSON */
                    response($.map(data, function(item) {
                        return {
                            value: item.name,
                            label: item.name
                        }
                    }))
                },
                error: function(xhr, textStatus, errorThrown) {
                    var errorMessage = "Ajax error: " + this.url + " : " + textStatus + " : " + errorThrown + " : " + xhr.statusText + " : " + xhr.status;

                    if (xhr.status != "0" || errorThrown != "abort") {
                        alert(errorMessage);
                    }
                }
            });
        },
        minLength: 2
    });
});

Asmx代码:

[WebService(Namespace = "http://localhost/v2/pages/main.aspx")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class researcher_list : System.Web.Services.WebService
{
    [WebMethod]
    public List<DBResearcher.Summary> FetchResList(string resName)
    {
        //SqlConnection connection;
        //SqlCommand command = null;
        //SqlDataReader myReader = null;
        //string sql;
        //StringBuilder sb = new StringBuilder();
        var tempSum = new DBResearcher();
        var allRes = DBResearcher.GetAllResearcher()
                        .Where(m => m.name.ToLower().Contains(resName.ToLower()));
        return allRes.ToList();
    }

    public static string[] GetCustomerNames()
    {
        string[] data = new string[] { "Andrew", "Ramona", "Russ", "Russell",  Raymond" };

        return data;

    }
}

web.config文件:

<httpHandlers>
  <!-- AJAX.Net Configuration -->
  <add verb="GET,POST" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
  <remove verb="*" path="*.asmx"/>
  <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  <add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpHandlers>

<!-- HTTP MODULES -->

 <httpModules>
  <!-- doesn't work if we restrict it by <location path=...> for some reason,
            so we have no choice but to do this at the root level. -->
  <!--<add name="HttpUploadModule" type="AssistedSolutions.SlickUpload.HttpUploadModule, AssistedSolutions.SlickUpload" />
    -->
  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

 </httpModules>

编辑 - 在自己运行asmx页面时出错

Stack Trace:

[HttpException (0x80004005): Failed to Execute URL.]
   System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.BeginExecuteUrl(String url, String method, String childHeaders, Boolean sendHeaders, Boolean addUserIndo, IntPtr token, String name, String authType, Byte[] entity, AsyncCallback cb, Object state) +2008569
   System.Web.HttpResponse.BeginExecuteUrlForEntireResponse(String pathOverride, NameValueCollection requestHeaders, AsyncCallback cb, Object state) +393
   System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state) +220
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8699714
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

2 个答案:

答案 0 :(得分:1)

尝试使用WebMethod属性标记您的方法,如下所示:

[WebMethod]
public static List<DBResearcher.Summary> FetchResList(string mail)
{
...
}

此外,您的参数需要匹配,因此请将resName更改为mail。

您还可以将jQuery合并到自动完成选择器中:

$('input:text').autocomplete(...)

编辑:

试试这段代码:

$('input:text').autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "researcher_list.asmx/FetchResList",
            data: "{ 'resName': '" + request.term + "' }",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                response($.map(data.d, function (item) {
                    return {
                        value: item.name
                    }
                }))
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }, minLength: 2
});

答案 1 :(得分:1)

我的答案是基于asp.net 3.5解决方案和jQuery 1.7.1版本假设而构建的。其他海报已经涵盖了很多内容。您的版本可能有所不同。这只是尝试使用完整的脚本和服务器端注释将注释放在答案中。

你有没有为你的课程装饰:

[WebService(Namespace = "http://mysite.com/researcher_list/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class researcher_list : WebService
{

装饰你的方法:(使用你需要的EnableSession IF ......)

[WebMethod(EnableSession = true)]
public List<DBResearcher.Summary> FetchResList(string resName)        {  

清理客户端脚本:

$('input:text').autocomplete({
    source: function(request, response) {
        var pString = '{ "resName": "' + request.term + '" }';
        $.ajax({
            url: "researcher_list.asmx/FetchResList",
            /* same root as the page? */
            data: pString,
            dataType: "jsond",
            type: "POST",
            contentType: "application/json",
            /* simplify */
            converters: { /* avoid the d or no d issue, works with 3.5 or prior this way */
                "json jsond": function(msg) {
                    return msg.hasOwnProperty('d') ? msg.d : msg;
                }
            },
            success: function(data) { /* assumes data always returned and it IS called item in the JSON */
                response($.map(data, function(item) {
                    return {
                        value: item.name,
                        label: item.name
                    };
                }));
            },
            minLength: 2,
            error: function(xhr, textStatus, errorThrown) {
                var errorMessage = "Ajax error: " + this.url + " : " + textStatus + " : " + errorThrown + " : " + xhr.statusText + " : " + xhr.status;
                if (xhr.status != "0" || errorThrown != "abort") {
                    alert(errorMessage);
                }
            }
        });
    }
});

除此之外,asp.net中还有Web.config设置,需要设置才能使Web服务正常运行 - 假设您已经完成了研究并且正常运行。如果不是,建议是创建一个简单的方法,将当前时间作为带有NO参数的字符串(data:“{}”,)返回,并通过ajax获取,以确保它在自动完成的复杂性分层之前有效。