Build a Lookup server control using the Ajax. NET Framework

Source: Internet
Author: User
I. Introduction

Today, Ajax is one of the most popular words in the software industry. However, this idea is not new, but for some reason, it became popular in the second half of last year. With the development of web-based application software, users often require richer and faster interfaces. AJAX can greatly improve users' web application experience.

For me, Ajax is brand new. Some time ago, due to the lack of trial tools and ready-to-use libraries, I read some articles to get some ideas. Recently, however, I have discovered Ajax. Net-a powerful framework that supports asynchronous callback.

In this article, I will describe how to create a search Control Based on AJAX. net. To build a search control, you need:

1. A server method that returns a list of matching records.

2. The javascript program is used to process the return and display a list of matching records.

3. There is an input field on the aspx/ascx page.

Here, I will not describe the installation of Ajax. Net because it is very simple and there are a lot of resources available for your reference on the Internet.

  Ii. Server

This part is relatively simple. I only need to create a method that returns an arraylist matching record and registers a class at the location of the method:

Public class main: Page {
Private void page_load (Object sender, eventargs e ){
Utility. registertypeforajax (typeof (main ));
}
[Ajaxmethod ()]
Public arraylist getsearchitems (string query ){
Arraylist items = getrecords ();
Arraylist matchitems = new arraylist ();
Foreach (string item in items ){
If (item. tolower (). startswith (query. tolower ()))
Matchitems. Add (item );
}
Return matchitems;
}
Private arraylist getrecords (){
Arraylist items = new arraylist ();
Items. Add ("Ted ");
Items. Add ("Teddy ");
Items. Add ("mark ");
Items. Add ("Alfred ");
Return items;
}
...

The getsearchitems method obtains a list of all records (from any source) and filters records starting with the query parameter. This query is the content and filter entered by the user in the input field.

  Iii. Client

First, I decided to write a very simple JavaScript-it will display a DIV, and the record found is exactly below the query input field. I think this is "close" to the goal, but it requires selecting one of the following items. The simplest thing is to convert all items to hyperlinks and fill the query domain with the correct click value. See the following code:

<Input id = search type = text name = SEARCH runat = "server"
AutoComplete = "off">
<Div id = "list"> </div>
AutoComplete = "off" is required to tell the browser not to display the possible values of this input field. Otherwise, our controls will not work.
Function getsearchitems_callback (response ){
VaR DIV = Document. getelementbyid ("list ");
Div. innerhtml = "";
If (response. value! = NULL & response. value. length> 0 ){
For (VAR I = 0; I <response. value. length; ++ I ){
Div. innerhtml + = "<a href = \" javascript: Fill ('"+ response. value [I] +"'); \ ">" +
Response. value [I] + "</a> <br/> ";
}
}

The javascript getsearchitems_callback function is called by the onkeydown event. This can be done in the background code or on the *. ASPX page. Now let's use the background code method.

Private void page_load (Object sender, eventargs e ){
Search. Attributes. Add ("onkeydown", "javascript: Main. getsearchitems (this. Value, getsearchitems_callback );");
Utility. registertypeforajax (typeof (main ));
}

The result looks as follows:

Although this situation is the simplest, it is not very useful. In this example, you simply enter some content and click a link in the displayed list. However, if this example is improved, it also requires some strong keyboard support. For example, you should be able to use the up/down key for list navigation, but use the Enter key.

4. Search for Javascript

I have never handled a keyboard problem in Javascript before (it is too complicated to write a large and complex script by myself ). I know JavaScript, but it is not as good as C #, so my first reaction is "searching for something on the internet that suits our needs ". It should be said that there are not many free scripts available. It took me about an hour to find a good script. The reference address is http://www.nsftools.com/tips/xmlhttplookup.js.

This script provides a function to query the server. I only made some modifications in the mainloop function to meet my requirements.

Mainloop = function (){
Val = escape (queryfield. value );
If (lastval! = Val & Searching = false ){
VaR response = Main. getseems EMS (VAL );
Showquerydiv ('smi', response. Value); lastval = val;
}
SetTimeout ('mainloop () ', 100 );
Return true;
};

This script should be enabled through the onload processor:

<Body onload = "initquerycode ('search')">

Finally, I spent a little time implementing the functions I needed. Unfortunately, this solution cannot be reused. Therefore, I decided to create a simple server control.

  V. server controls

This Ajax search server control is very simple. The following sections of the original solution can be further customized:

· Name of the callback function.

· Path of the Javascript file.

· Match the background of the list with highlighted, div padding, and other colors.

The specific implementation is quite simple. First, we can derive our controls from textbox. Then, we only need to set some variables and register some JavaScript Functions.

Using system;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Namespace play {
/// <Summary>
/// Ajaxlookup. CS
/// </Summary>
Public class ajaxlookup: textbox {
Private string scriptfile = "";
Private string callbackfunction = "";
Private string backgroundcolor = "# Eee ";
Private string highlightcolor = "# CCC ";
Private string font = "verdana ";
Private string divpadding = "2px ";
Private string divborder = "1px solid # CCC ";
Public String scriptfile {
Get {return scriptfile ;}
Set {scriptfile = value ;}
}
Public String callbackfunction {
Get {return callbackfunction ;}
Set {callbackfunction = value ;}
}
Public String backgroundcolor {
Get {return backgroundcolor ;}
Set {backgroundcolor = value ;}
}
Public String highlightcolor {
Get {return highlightcolor ;}
Set {highlightcolor = value ;}
}
Public String divfont {
Get {return font ;}
Set {font = value ;}
}
Public String divpadding {
Get {return divpadding ;}
Set {divpadding = value ;}
}
Public String divborder {
Get {return divborder ;}
Set {divborder = value ;}
}
Public ajaxlookup (){
This. Attributes. Add ("AutoComplete", "off ");
}
Protected override void render (htmltextwriter writer ){
Base. Render (writer );
// Bind a script containing almost all logic
Page. registerstartupscript ("loadscript", "<script language = 'javascript 'src = '" + scriptfile + "'>" +
"</SCRIPT> ");
// Includes UI settings
String styles = string. Format (@ "<script language = 'javascript '> var div_bg_color =' {0 }';
VaR div_highlight_color = '{1 }';
VaR div_font = '{2 }';
VaR div_padding = '{3 }';
VaR div_border = '{4 }';
</SCRIPT> ",
Backgroundcolor, highlightcolor, divfont,
Divpadding, divborder );
Page. registerstartupscript ("lookupstyles", Styles );
// Initialize the return process
Page. registerstartupscript ("registerscript ",
"<Script language = 'javascript '>" +
"Initquerycode ('" + this. clientid + "') </SCRIPT> ");
// Set the correct callback function
Page. registerstartupscript ("registercallback ",
@ "<Script language = 'javascript '>
Mainloop = function (){
Val = escape (queryfield. value );
If (lastval! = Val & Searching = false ){
VaR response = "+ callbackfunction + @" (VAL );
Showquerydiv ('smi', response. Value); lastval = val;
}
SetTimeout ('mainloop () ', 100 );
Return true ;};
</SCRIPT> ");
}
}

This control can be used as follows:

<Ajax: ajaxlookup
Runat = "server"
Id = "Search"
Backgroundcolor = "# Eee"
Divborder = "1px solid # CCC"
Divpadding = "2px"
Divfont = "Arial"
Highlightcolor = "# C30"
Callbackfunction = "Main. getsearchitems"
Scriptfile = "lookup. js"/>

Here is what the query control looks like in the running result:

The implementation here is not ideal, but it is a good start. You can improve it by adding other parameters.

  Vi. Conclusion

In fact, Ajax. Net also has many other functions. As a learning method, it is reasonable to start with the simplest Search control, but I hope that in the future, many projects will be implemented based on AJAX technology in uidesign.

From: http://dev.yesky.com/msdn/220/2402720_1.shtml

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.