【问题标题】:Autocomplete jquery in asp.net, source from code behind在 asp.net 中自动完成 jquery,源代码来自后面
【发布时间】:2012-03-29 19:54:47
【问题描述】:

虽然这个论坛有很多jquery自动完成代码。但是,我没有找到适合我的 SharePoint/ASP.NET 网页案例的任何内容。我关注了jquery autocomplete link。这很有帮助。但是请看

我的代码:

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" 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 () {
        $("asp:TextBox#TextBox3").autocomplete({
            source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
        });
    });

</script>
 </asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<table>
      <tr><td>
        <asp:Label ID="Label4" runat="server" Text="Qode"></asp:Label></td><td>
           <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

        </td></tr>
</table>

问题

1. Can I use the code ` $("asp:TextBox#TextBox3")?`
2. If the source comes from code behind instead of hard copy strings, how to do it?

让我们在后面的代码中说:

        string[] source = new string[5];
        source[0] = "c++";
        source[1] = "java";
        source[2] = "php";
        source[3] = "coldfusion";
        source[4] = "javascript";

那么如何将数组传递给jquery代码呢? 非常感谢。

【问题讨论】:

    标签: c# jquery asp.net jquery-ui sharepoint


    【解决方案1】:

    关于您的第一个问题,如果您使用的是 ASP.net 版本 4 或更高版本,您可以将文本框的 ClientIDMode 设置为“静态”,它将强制服务器将 ClientID 呈现为与服务器标识。然后你就可以在你的jQuery代码中正常引用它了。

    例如

    &lt;asp:TextBox ID="TextBox3" runat="server" ClientIdMode="static"&gt;`

    $("#TextBox3")  // select your text box with standard jQuery id selector
    

    如果您使用的是旧版本的 ASP.net,您可以将服务器端代码插入到您的 .aspx 中以访问生成的动态客户端 ID。您也可以将其添加到您的 jQuery 选择器中,但会有所不同。

    $("#<%= Textbox3.ClientID %>")
    

    这应该将正确的客户端 ID 呈现给浏览器并由 jQuery 处理。

    至于您的第二个问题,我个人会将数组序列化为 JSON 并将其发送到 jQuery。一个很好的库是 Json.Net (http://json.codeplex.com/),其中包含如何使用该库的示例。

    【讨论】:

    • 我使用了 $(document).ready(function () { $("").autocomplete({ 但它不起作用。
    • 再次检查我的代码,我在选择器中有错字。
    • 如果您无法使用 jason.net 等第三方组件,您可以使用JavaScriptSerializer。如果您的字符串是动态的,您可以选择托管一个瘦页面方法,然后您可以使用 ajax 并动态获取结果。
    • 一定要看看 Roman 对 PageMethod 使用 Ajax 调用的想法。这将为您的代码提供更大的灵活性,让您的自动完成功能由 SQL、XML 等数据驱动。JavaScriptSerializer 类当然也可以很好地工作,但我刚刚习惯使用 Json.net,因为我接手的早期项目。请记住,尽管 JavaScriptSerializer 是 .net 3.5 的新增功能,因此如果您使用的是旧版本的框架,您将无法在本地使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多