My AutoComplete-source code available

Source: Internet
Author: User
Tags blank page

The AutoComplete control is already widely used on the Internet. It was used once in a project, but it is not well encapsulated. I recently learned how to develop a control. I feel that this control will be used in the future, so I tried to write one.

Although this control is available on the Internet at will, in order to integrate it into your own framework, it is also necessary to develop on your own, and the development process is also an opportunity to learn and improve.

 

First, let's demonstrate the methods and effects.

1. create a blank page and introduce necessary scripts and style files (jquery and its own script library. This script library contains not only the scripts used by the auctocomplete control ), then drag or hand-write an AutoComplete control, which is essentially an extended Textbox Control.

<title></title> 
<script type ="text/javascript" src ="http://www.cnblogs.com/js/jquery-1.4.1-vsdoc.js"></script>
<script type ="text/javascript" src ="http://www.cnblogs.com/js/Core.js"></script>
<link href="http://www.cnblogs.com/style/web.css" rel="stylesheet" type="text/css" />
<body>
<form id="form1" runat="server">
<Jiuzh:AutoComplete runat="server" ID ="acExample" ></Jiuzh:AutoComplete>
</form>
</body>

 

2. double-click the control to add an ontextchanged event function and set the minstart attribute of the control. This attribute indicates the minimum number of characters that can be queried, there is also a Params attribute used to bind additional parameters for query, which is not used here. The HTML code and C # Code are as follows:

    <form id="form1" runat="server">
<Jiuzh:AutoComplete runat="server" ID ="acExample" ontextchanged="acExample_TextChanged" MinStart="2" ></Jiuzh:AutoComplete>
</form>
        protected List<string> acExample_TextChanged(object sender)
{
List<string> result = new List<string>();
result.Add("1213");
result.Add("1234");
result.Add("5345");
result.Add("1241");
return result.Where(s => s.Contains(acExample.Text)).ToList();
}

Success: Start the page and enter 12 in the text box. The result is shown in.

 

 

How to use it.

= ======================================

First, the technology used by this control is very simple, mainly the Ajax interface of jquery and the control development technology of ASP. NET.

I think for new users, it must be very interested in the ontextchanged event function of the control. The autopostback attribute is not set to true. How does it trigger server events? In addition, how does the function signature of the event change, there is only one sender parameter.

 

First, let's take a look at the HTML code generated on the page.

<input onkeyup="AutoComplate(this,2,{})" name="acExample" type="text" id="acExample" />

See, an input control. It is bound to the onkeyup event when the page is generated. The onkeyup event executes the autocomplate function. This function has three parameters, not to mention the first parameter, the second parameter is the set minstart parameter, and the third parameter is the additional parameter bound during the query.

Next, let's look at the autocomplate function.

 function AutoComplate(obj, len, param) {
var ctl = $(obj);
var val = ctl.val();
var ctlId = ctl.attr("id");
if (val.length == 0) {
$("#" + ctlId + "_Auto").hide();
return;
}
if (val.length < len)
return;
var div = $("#" + ctlId + "_Auto");
if (div.length == 0) {
div = $("<div id=\"" + ctlId + "_Auto\" style =\"position:absolute; display:none; border:1px solid #817f82; background-color:#ffffff; width:200px\"></div>");
$('body').append(div);
}
param ["__EVENTTARGET"]=ctlId;
param[ctlId] = val;
var wu_nopar = window.location.href.split("?")[0].split("/");
var pageName = wu_nopar[wu_nopar.length - 1];
$.post(pageName+"?action=list", param, function (data) {
var result = eval(data);
if (result.length > 0) {
div.html("");
var table = $("<table style='width:100%' ><tbody></tbody></table>");
for (var i = 0; i < result.length; i++) {
var tr = $("<tr><td >" + result[i] + "</td></tr>");
tr.mouseover(function () {
$(this).addClass('JZac');
});
tr.mouseout(function () {
$(this).removeClass('JZac');
});
tr.click(function () {
$(obj).val($(this).children().eq(0).html());
div.hide();
});
table.append(tr);
}
div.append(table);
var of = $(obj).offset();
var top = of.top + $(obj).height();
div.css("top", top + 5);
div.css("left", of.left);
div.width($(obj).width());
div.show();
}
else
div.hide();
});
}

For those familiar with jquery, the above Code does not have much to explain. The key is the two sentences.

     param ["__EVENTTARGET"]=ctlId;
param[ctlId] = val;

The param parameter I explained just now is an additional parameter for the query, but in this AutoComplete function, I added two additional parameters for it. The first parameter is named _ eventtarget, the value is the current control ID, the second parameter is the current control ID, and the value is the control text value. With these two parameters submitted in post mode, the ontextchanged event of our AutoComplete control is triggered on the server side. That is to say, in the autocomplete function, I simulate the data that triggers the Control Server event and submit it in Ajax mode.

 

Finally, let's look at the source code of the control. First, I defined a delegate to replace the default delegate.

public delegate List <string > AutoCompleteHandler(object sender);

The following is the control code.

[ToolboxData("<{0}:AutoComplete runat=server></{0}:AutoComplete>")]
public class AutoComplete : TextBox
{
public new event AutoCompleteHandler TextChanged;

private Params _params=new Params ();
public Params Params
{
get
{
return _params;
}
}

[TypeConverter (typeof (uint ))]
public string MinStart { get; set; }

protected virtual void OnAutoCompleteChanged(EventArgs e)
{
if (TextChanged != null)
{
List<string> result = TextChanged(this);
JavaScriptSerializer ser = new JavaScriptSerializer();
string json = ser.Serialize(result);
Context.Response.ContentType = "text/plain";
Context.Response.Write(json);
Context.Response.End();
}
}

protected override void RaisePostDataChangedEvent()
{
OnAutoCompleteChanged(EventArgs.Empty);
// base.RaisePostDataChangedEvent();
}

public override void RenderControl(HtmlTextWriter writer)
{
StringBuilder sb=new StringBuilder ();
for (int i = 0; i < Params.Count; i++)
{
sb.AppendFormat("{0}:{1}", Params .Keys [i], Params [i]);
}
writer.AddAttribute("onkeyup", "AutoComplate(this,"+MinStart+",{" + sb.ToString () + "})");
base.RenderControl(writer);
}


}

The first is the public new event autocompletehandler textchanged. In this example, the new keyword is used to execute the textchanged event to execute the delegate I previously defined. Then, in the onautocompletechanged function, get the result returned by the textchanged event, and return data with response. End.

================================================================== ====================================

The above is the introduction of the Control. I hope it will be helpful to you. If there is anything wrong, please point it out.

Because someone needs a complete code package, there is a demo, the following is the link: http://files.cnblogs.com/xxfss2/Demo.rar

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.