简体   繁体   中英

Autocomplete jquery in asp.net, source from code behind

Although there are a lot of jquery autocomplete code in this forum. However I haven't found anything fitting to my SharePoint/ASP.NET web page case. I followed the jquery autocomplete link . It is helpful. But please look at

My code:

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

Question

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?

Let's say in code behind:

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

Then how to pass the array to jquery code? Many thanks.

With regards to your first question, if you're using ASP.net version 4 or higher you can set the ClientIDMode of the textbox to "static" and it will force the server to render the ClientID to be the same as the server ID. Then you can reference it normally in your jQuery code.

Ex.

<asp:TextBox ID="TextBox3" runat="server" ClientIdMode="static"> `

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

If you're using an older version of ASP.net, you can insert server-side code into your .aspx to access the dynamic clientID that is generated. You would add this to your jQuery selector as well, but it would be a little different.

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

This should render the proper client ID to the browser and be handled by jQuery.

As for your second question, personally I would serialize the array to JSON and send that to jQuery. A good library do so is Json.Net ( http://json.codeplex.com/ ), which has examples of how to use the library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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