由于项目需要,制作一个复杂的 TextBox 自定义控件,功能是控件内部可以通过国家、省市联动来获取邮政编码,显示在 Text 中,该控件的对外接口就是 Text 属性,其他程序可以通过 Text 属性来 设置或获取邮政编码。
说明:由于项目需要,制作一个复杂的 TextBox 自定义控件,功能是控件内部可以通过国家、省市联动来获取邮政编码,显示在 Text 中,该控件的对外接口就是 Text 属性,其他程序可以通过 Text 属性来 设置或获取邮政编码。
源码下载:
自定义控件获取邮政编码(包含国家、省市联动)
其中有一些问题,希望能和大家一起探讨。
该控件分三大块:控件逻辑代码(GetZip.cs)、js 代码(ajaxData.js)和 异步数据获取代码(ZipCode.ashx),
详细如下:
1、GetZip.cs:
Code
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Text;
5using System.Web;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Drawing;
9using System.Collections;
10using System.Data;
11using System.Data.SqlClient;
12using System.Web.UI.HtmlControls;
13using DBUtility;
14namespace Zip
15{
16 [DefaultProperty("Text")]
17 [ToolboxData("<{0}:GetZip runat=server></{0}:GetZip>")]
18 public class GetZip : WebControl, ICallbackEventHandler, INamingContainer, ICompositeControlDesignerAccessor
19 {
20 //private int _PollingInterval = 5;
21 private string str;
22 private string targetObject;
23 private string type;
24 /**//// <exclude />
25 protected override HtmlTextWriterTag TagKey
26 {
27 get
28 {
29 return HtmlTextWriterTag.Span;
30 }
31 }
32 [Bindable(true)]
33 [Category("Appearance")]
34 [DefaultValue("")]
35 [Localizable(true)]
36 public string Text
37 {
38 get
39 {
40 //String s = (String)ViewState["Text"];
41 //return ((s == null) ? String.Empty : s);
42 return text.Text;
43 }
44
45 set
46 {
47 //ViewState["Text"] = value;
48 text.Text = value;
49 }
50 }
51 public override bool EnableViewState
52 {
53 get { return base.EnableViewState; }
54 set { base.EnableViewState = true; }
55 }
56 private Color _fontColor = Color.Black;//声明字体颜色变量
57 private Color _backColor = Color.White;//声明控件背景变量
58 private WebControl container = new WebControl(HtmlTextWriterTag.Span);
59 private WebControl floatContainer = new WebControl(HtmlTextWriterTag.Span);
60 private HtmlInputButton button = new HtmlInputButton();
61 private HtmlInputButton getButton = new HtmlInputButton();
62 private TextBox text = new TextBox();
63 private TextBox codeText = new TextBox();
64 private DropDownList countryDropDownList = new DropDownList();
65 private DropDownList stateDropDownList = new DropDownList();
66 private DropDownList cityDropDownList = new DropDownList();
67 private Label countryLabel = new Label();
68 private Label stateLabel = new Label();
69 private Label cityLabel = new Label();
70 private Label zipCodeLabel = new Label();
71 protected internal WebControl Container
72 {
73 get
74 {
75 this.EnsureChildControls();
76 return this.container;
77 }
78 }
79 protected internal WebControl FloatContainer
80 {
81 get
82 {
83 this.EnsureChildControls();
84 return this.floatContainer;
85 }
86 }
87 protected internal HtmlInputButton Button
88 {
89 get
90 {
91 this.EnsureChildControls();
92 return this.button;
93 }
94 }
95 protected internal HtmlInputButton GetButton
96 {
97 get
98 {
99 this.EnsureChildControls();
100 return this.getButton;
101 }
102 }
103 protected internal TextBox OutText
104 {
105 get
106 {
107 this.EnsureChildControls();
108 return this.text;
109 }
110 }
111 protected internal TextBox CodeText
112 {
113 get
114 {
115 this.EnsureChildControls();
116 return this.codeText;
117 }
118 }
119 protected internal DropDownList CountryDropDownList
120 {
121 get
122 {
123 this.EnsureChildControls();
124 return this.countryDropDownList;
125 }
126 }
127 protected internal DropDownList StateDropDownList
128 {
129 get
130 {
131 this.EnsureChildControls();
132 return this.stateDropDownList;
133 }
134 }
135 protected internal DropDownList CityDropDownList
136 {
137 get
138 {
139 this.EnsureChildControls();
140 return this.cityDropDownList;
141 }
142 }
143 protected internal Label CountryLabel
144 {
145 get
146 {
147 this.EnsureChildControls();
148 return this.countryLabel;
149 }
150 }
151 protected internal Label StateLabel
152 {
153 get
154 {
155 this.EnsureChildControls();
156 return this.StateLabel;
157 }
158 }
159 protected internal Label CityLabel
160 {
161 get
162 {
163 this.EnsureChildControls();
164 return this.cityLabel;
165 }
166 }
167 protected internal Label ZipCodeLabel
168 {
169 get
170 {
171 this.EnsureChildControls();
172 return this.zipCodeLabel;
173 }
174 }
175 public GetZip()
176 {
177
178 }
179 //根据自己的需要添加或重载符合控件的公共属性#region//根据自己的需要添加或重载符合控件的公共属性
180 //字体颜色属性
181 [Bindable(false), Category("Appearance"), DefaultValue("")]
182 public override Color ForeColor
183 {
184 get
185 {
186 return this._fontColor;
187 }
188 set
189 {
190 this._fontColor = value;
191 }
192 }
193
194 //控件背景属性
195 [Bindable(false), Category("Appearance"), DefaultValue("")]
196 public override Color BackColor
197 {
198 get
199 {
200 return this._backColor;
201 }
202 set
203 {
204 this._backColor = value;
205 }
206 }
207 //控件宽度属性
208
209 [Bindable(false),
210
211 Category("Appearance"),
212
213 DefaultValue("")]
214
215 public override Unit Width
216 {
217
218 get
219 {
220
221 return this.container.Width;
222
223 }
224
225 set
226 {
227
228 this.container.Width = value;
229
230 }
231
232 }
233
234 //控件高度属性
235
236 [Bindable(false),
237
238 Category("Appearance"),
239
240 DefaultValue("")]
241
242 public override Unit Height
243 {
244
245 get
246 {
247
248 return this.container.Height;
249
250 }
251
252 set
253 {
254
255 this.container.Height = value;
256
257 }
258
259 }
260
261 //控件边框颜色属性
262
263 [Bindable(false),
264
265 Category("Appearance"),
266
267 DefaultValue("")]
268
269 public override Color BorderColor
270 {
271
272 get
273 {
274
275 return this.container.BorderColor;
276
277 }
278
279 set
280 {
281
282 this.container.BorderColor = value;
283
284 }
285
286 }
287
288 //控件边框样式属性
289
290 [Bindable(false),
291
292 Category("Appearance"),
293
294 DefaultValue("")]
295
296 public override BorderStyle BorderStyle
297 {
298
299 get
300 {
301
302 return this.container.BorderStyle;
303
304 }
305
306 set
307 {
308
309 this.container.BorderStyle = value;
310
311 }
312
313 }
314
315 //控件边框宽度属性
316
317 [Bindable(false),
318
319 Category("Appearance"),
320
321 DefaultValue("")]
322
323 public override Unit BorderWidth
324 {
325
326 get
327 {
328
329 return this.container.BorderWidth;
330
331 }
332 set
333 {
334
335 this.container.BorderWidth = value;
336
337 }
338 }
339 #endregion
340 /**//// <exclude/>
341 protected override void Render(HtmlTextWriter writer)
342 {
343
344 this.EnsureChildControls();
345 RenderBeginTag(writer);
346 RenderChildren(writer);
347 RenderEndTag(writer);
348 }
349 protected override void OnPreRender(EventArgs e)
350 {
351 base.OnPreRender(e);
352 RegisterScript();
353 }
354
355 private void RegisterScript()
356 {
357 /**///// Add style sheet to parent page
358
359 //string cssUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "WhoIsLooking.Stylesheet.css");
360
361 //HtmlLink cssLink = new HtmlLink();
362
363 //cssLink.Href = cssUrl;
364
365 //cssLink.Attributes.Add("rel", "stylesheet");
366
367 //cssLink.Attributes.Add("type", "text/css");
368
369 //this.Page.Header.Controls.Add(cssLink);
370
371 /**///// Add class name
372
373 //this.CssClass = "Stylesheet";
374 // Force Session State to create Session Id
375 //Context.Session["WhoIsLooking"] = "1";
376 //Page.ClientScript.GetWebResourceUrl(this.GetType(), "Zip.js");
377 //Add Javascript include
378 string scriptUrl2 = Page.ClientScript.GetWebResourceUrl(this.GetType(), "Zip.ajaxData.js");
379 Page.ClientScript.RegisterClientScriptInclude("ajaxData", scriptUrl2);
380 //string[] parastr = new string[2]{"str","targerObject"};
381 //String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arr", "ShowValues", null, true);
382 //String callbackScript;
383 /**/////string[] serverpara = new string[3] { "id", "targetObj","type" };
384 //callbackScript = "function CallServer(arr,context)" +
385 // "{ " + cbReference + ";}";
386 //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
387 String scriptKey = "zip.Panel";
388 String arrayDeclaration = @"{ " +
389 " ID:'" + this.ClientID + "'" +
390 ", ContainerID:'" + this.Container.ClientID + "'" +
391 ", FloatContainerID:'" + this.FloatContainer.ClientID + "'" +
392 ", TextID:'" + this.OutText.ClientID + "'" +
393 ", CodeTextID:'" + this.CodeText.ClientID + "'" +
394 ", ButtonID:'" + this.Button.ClientID + "'" +
395 ", GetButtonID:'" + this.GetButton.ClientID + "'" +
396 ", CountryID:'" + this.CountryDropDownList.ClientID + "'" +
397 ", StateID:'" + this.StateDropDownList.ClientID + "'" +
398 ", CityID:'" + this.CityDropDownList.ClientID + "'" +
399 //", ListSize:" + this.Rows +
400 " }";
401 Page.ClientScript.RegisterStartupScript(typeof(Panel), scriptKey, "Zip_FloatPanel_Init();", true);
402 Page.ClientScript.RegisterArrayDeclaration("Zip_Controls", arrayDeclaration);
403
404 }
405 private void GetCountryList()
406 {
407 DataSet ds = SqlHelper.Query(SqlHelper.LocalSqlServer, "select * from Country_State_City_View where GroupName='Country'");
408
409 //ds.ReadXml("Country.xml");
410 if (ds != null)
411 {
412 if (ds.Tables[0].Rows.Count > 0)
413 {
414 for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
415 {
416 ListItem listItem = new ListItem();
417 listItem.Text = ds.Tables[0].Rows[i]["CaptionMessageSignName"].ToString();
418 listItem.Value = ds.Tables[0].Rows[i]["CaptionMessageID"].ToString();
419 countryDropDownList.Items.Add(listItem);
420 }
421 }
422 }
423 }
424 private void GeValueList(string eventArgument)
425 {
426 string[] stringarr = eventArgument.Split(',');
427 string id = stringarr[0];
428 targetObject = stringarr[1];
429 type = stringarr[2];
430 string groupName = "";
431 if (type == "1")
432 {
433 groupName = "State";
434 }
435 else if (type == "2")
436 {
437 groupName = "City";
438 }
439 DataSet ds = new DataSet();
440 StringBuilder sb = new StringBuilder();
441 if (type == "3")//get zip code by city
442 {
443 ds = SqlHelper.Query(SqlHelper.LocalSqlServer, "select * from Country_State_City_View where CaptionMessageID='" + id + "'");
444 //ds.ReadXml("City.xml");
445 if (ds != null)
446 {
447 if (ds.Tables[0].Rows.Count > 0)
448 {
449 //DataView dv = ds.Tables[0].DefaultView;
450 //dv.RowFilter = "CityID = " + id;
451 sb.Append(",");
452 sb.Append(ds.Tables[0].Rows[0]["CaptionMessage_JokerField_3"].ToString());
453 }
454 }
455 }
456 else
457 {
458 ds = SqlHelper.Query(SqlHelper.LocalSqlServer, "select * from Country_State_City_View where GroupName='" + groupName + "' and GroupFatherID='" + id + "'");
459 //ds.ReadXml("State.xml");
460 if (ds != null)
461 {
462 if (ds.Tables[0].Rows.Count > 0)
463 {
464 //DataView dv = ds.Tables[0].DefaultView;
465 //dv.RowFilter = "CountryID = " + id;
466 for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
467 {
468 sb.Append(",");
469 sb.Append(ds.Tables[0].Rows[i]["CaptionMessageID"].ToString());
470 sb.Append("|");
471 sb.Append(ds.Tables[0].Rows[i]["CaptionMessageSignName"].ToString());
472 }
473 }
474 }
475 }
476 str = sb.ToString().Substring(1);
477 }
478 /**//// <summary>
479 /// 保存自页回发到服务器后发生的任何服务器控件视图状态更改。
480 /// </summary>
481 /// <returns>返回服务器控件的当前视图状态。</returns>
482 protected override object SaveViewState()
483 {
484 object[] vState = new object[] { base.SaveViewState() };
485 return vState;
486 }
487
488 /**//// <summary>
489 ///从 SaveViewState 方法保存的上一个页请求还原视图状态信息。
490 /// </summary>
491 /// <param name="savedState">表示要还原的控件状态的 Object</param>
492 protected override void LoadViewState(object savedState)
493 {
494 if (savedState != null)
495 {
496 object[] vState = (object[])savedState;
497 if (vState[0] != null)
498 base.LoadViewState(vState[0]);
499 }
500 }
501 protected override void CreateChildControls()
502 {
503 this.Controls.Clear();
504
505 base.CreateChildControls();
506
507 container.ID = "Container";
508 container.Style[HtmlTextWriterStyle.Position] = "relative";
509 this.Controls.Add(container);
510
511 text.ID = "Text";
512 container.Controls.Add(text);
513
514 button.ID = "Button";
515 button.Value = "get zip code";
516 button.Attributes.Add("onclick", "Zip_Button_Toggle(this);");
517 container.Controls.Add(button);
518
519 floatContainer.ID = "FloatContainer";
520 floatContainer.Style[HtmlTextWriterStyle.Position] = "relative";
521 floatContainer.Width = 80;
522 floatContainer.BorderWidth = 1;
523 floatContainer.BackColor = Color.Azure;
524 this.container.Controls.Add(floatContainer);
525
526 countryLabel.ID = "CountryLabel";
527 countryLabel.Text = "Country:";
528 //floatContainer.Controls.Add(countryLabel);
529
530 countryDropDownList.EnableViewState = true;
531 countryDropDownList.ID = "CountryDropDownList";
532 countryDropDownList.EnableViewState = true;
533 //floatContainer.Controls.Add(countryDropDownList);
534
535 //floatContainer.Controls.Add(HtmlTextWriterTag.Br);
536
537 stateLabel.ID = "StateLabel";
538 stateLabel.Text = "State:";
539 //floatContainer.Controls.Add(stateLabel);
540
541 stateDropDownList.EnableViewState = true;
542 stateDropDownList.ID = "StateDropDownList";
543 stateDropDownList.EnableViewState = true;
544 //floatContainer.Controls.Add(stateDropDownList);
545
546 //floatContainer.Controls.Add(HtmlTextWriterTag.Br);
547
548 cityLabel.ID = "CityLabel";
549 cityLabel.Text = "City:";
550 floatContainer.Controls.Add(cityLabel);
551
552 cityDropDownList.EnableViewState = true;
553 cityDropDownList.EnableViewState = true;
554 cityDropDownList.ID = "CityDropDownList";
555 //floatContainer.Controls.Add(cityDropDownList);
556
557 //floatContainer.Controls.Add(HtmlTextWriterTag.Br);
558
559 zipCodeLabel.ID = "ZipCodeLabel";
560 zipCodeLabel.Text = "Zip Code:";
561 //floatContainer.Controls.Add(zipCodeLabel);
562
563 codeText.ID = "CodeText";
564 codeText.ReadOnly = true;
565 //codeText.Attributes["autocomplete"] = "off";
566 //floatContainer.Controls.Add(codeText);
567 //text.TextChanged += new EventHandler(this.raiseTextChanged);
568
569 //floatContainer.Controls.Add(HtmlTextWriterTag.Br);
570
571 getButton.ID = "GetButton";
572 getButton.Value = "select code";
573 getButton.Attributes.Add("onclick", "getZipCode(" + text.ClientID + "," + codeText.ClientID + ");");
574
575 HtmlTable showTable = new HtmlTable();
576 showTable.Rows.Add(new HtmlTableRow());
577 showTable.Rows.Add(new HtmlTableRow());
578 showTable.Rows.Add(new HtmlTableRow());
579 showTable.Rows.Add(new HtmlTableRow());
580 showTable.Rows.Add(new HtmlTableRow());
581
582 showTable.Rows[0].Cells.Add(new HtmlTableCell());
583 showTable.Rows[0].Cells.Add(new HtmlTableCell());
584 showTable.Rows[1].Cells.Add(new HtmlTableCell());
585 showTable.Rows[1].Cells.Add(new HtmlTableCell());
586 showTable.Rows[2].Cells.Add(new HtmlTableCell());
587 showTable.Rows[2].Cells.Add(new HtmlTableCell());
588 showTable.Rows[3].Cells.Add(new HtmlTableCell());
589 showTable.Rows[3].Cells.Add(new HtmlTableCell());
590 showTable.Rows[4].Cells.Add(new HtmlTableCell());
591
592 showTable.Rows[0].Cells[0].Controls.Add(countryLabel);
593 showTable.Rows[0].Cells[1].Controls.Add(countryDropDownList);
594 showTable.Rows[1].Cells[0].Controls.Add(stateLabel);
595 showTable.Rows[1].Cells[1].Controls.Add(stateDropDownList);
596 showTable.Rows[2].Cells[0].Controls.Add(cityLabel);
597 showTable.Rows[2].Cells[1].Controls.Add(cityDropDownList);
598 showTable.Rows[3].Cells[0].Controls.Add(zipCodeLabel);
599 showTable.Rows[3].Cells[1].Controls.Add(codeText);
600 showTable.Rows[4].Cells[0].Controls.Add(getButton);
601 floatContainer.Controls.Add(showTable);
602
603 countryDropDownList.Items.Add(new ListItem("Select Country", "0"));
604 countryDropDownList.Attributes.Add("onchange", "return GetValues(" + this.countryDropDownList.ClientID + "," + this.stateDropDownList.ClientID + ",\"1\")");
605 stateDropDownList.Attributes.Add("onchange", "return GetValues(" + this.stateDropDownList.ClientID + "," + this.cityDropDownList.ClientID + ",\"2\")");
606 cityDropDownList.Attributes.Add("onchange", "return GetValues(" + this.cityDropDownList.ClientID + "," + this.codeText.ClientID + ",\"3\")");
607 getButton.Attributes.Add("onclick", "getZipCode(" + text.ClientID + "," + codeText.ClientID + ");");
608 this.GetCountryList();
609 }
610 /**//// <exclude />
611 public override void DataBind()
612 {
613 this.OnDataBinding(EventArgs.Empty);
614 this.EnsureChildControls();
615 this.DataBindChildren();
616 }
617 private HtmlTextWriter getCorrectTagWriter(HtmlTextWriter writer)
618 {
619
620 HtmlTextWriter tagWriter = writer;
621
622 if (writer is System.Web.UI.Html32TextWriter)
623 {
624 HttpBrowserCapabilities browser = this.Page.Request.Browser;
625 if (browser.W3CDomVersion.Major > 0)
626 {
627 tagWriter = new HtmlTextWriter(writer.InnerWriter);
628 }
629 else if (String.Compare(browser.Browser, "netscape", StringComparison.OrdinalIgnoreCase) == 0)
630 {
631 if (browser.MajorVersion >= 5)
632 {
633 tagWriter = new HtmlTextWriter(writer.InnerWriter);
634 }
635 }
636 }
637
638 return tagWriter;
639 }
640 /**//// <exclude/>
641 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
642 protected override void OnLoad(System.EventArgs e)
643 {
644 //this.isLoaded = true;
645 base.OnLoad(e);
646 }
647 /**//// <exclude/>
648 protected override void AddAttributesToRender(HtmlTextWriter writer)
649 {
650
651 if (this.Page != null)
652 {
653 this.Page.VerifyRenderingInServerForm(this);
654 }
655
656 base.AddAttributesToRender(writer);
657 }
658 /**//// <exclude />
659 protected virtual void RecreateChildControls()
660 {
661 base.ChildControlsCreated = false;
662 this.EnsureChildControls();
663 }
664
665 /**////// <exclude />
666 //void ICompositeControlDesignerAccessor.RecreateChildControls()
667 //{
668 // this.RecreateChildControls();
669 //}
670 /**//// <exclude />
671 public override ControlCollection Controls
672 {
673 get
674 {
675 this.EnsureChildControls();
676 return base.Controls;
677 }
678 }
679
680 ICompositeControlDesignerAccessor 成员#region ICompositeControlDesignerAccessor 成员
681
682 /**//// <exclude />
683 void ICompositeControlDesignerAccessor.RecreateChildControls()
684 {
685 this.RecreateChildControls();
686 }
687
688 #endregion
689
690 ICallbackEventHandler 成员#region ICallbackEventHandler 成员
691
692 string ICallbackEventHandler.GetCallbackResult()
693 {
694 string[] ss = new string[3] { str, targetObject, type };
695
696 return string.Join(",", ss);
697 }
698
699 void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
700 {
701 GeValueList(eventArgument);
702 }
703
704 #endregion
705 }
706}
707
2、ajaxData.js
var xmlDom;
function createXMLHTTP()
{
if(window.XMLHttpRequest)
{
xmlDom=new XMLHttpRequest();//mozilla浏览器
}
else if(window.ActiveXObject)
{
try
{
xmlDom=new ActiveXObject("Msxml2.XMLHTTP");//IE老版本
}
catch(e)
{}
try
{
xmlDom=new ActiveXObject("Microsoft.XMLHTTP");//IE新版本
}
catch(e)
{}
if(!xmlDom)
{
window.alert("不能创建XMLHttpRequest对象实例!");
return false;
}
}
}
function GetValues(obj,targetObj,type)
{
if(obj.value!="")
{
createXMLHTTP();
var strURL="UserFunction/HTTPProcess/ZipCode.ashx?id="+obj.value+"&type="+type;
xmlDom.open("GET",strURL,true);
xmlDom.onreadystatechange = function(){ShowValues(targetObj,type);};
xmlDom.send(null);
}
}
function ShowValues(targetObj,type)
{
if (xmlDom.readyState == 4 && xmlDom.status == 200)
{
var arr = xmlDom.responseText;
if(arr != ""|| arr!=null)
{
// if(arr.indexOf("=")>0)
// {
// arr = arr.substr(arr.indexOf("=")+1);
// }
var array = arr.split(",");
var result = array;
// var targetObj = document.getElementById(array[array.length-2]);
// var type = array[array.length-1];
if(targetObj!=null)
{
if(type=="3")
{
targetObj.value = result[0];
}
else
{
delValues(targetObj);//delete
// var piArray = result.split(",");
if(type=="1")
{
targetObj.options.add(new Option("Select a State/Province","0"));
}
else if(type=="2")
{
targetObj.options.add(new Option("Select a Metro or City","0"));
}
for(var i=0;i<result.length;i++)
{
var ary1 = result[i].toString().split("|");
targetObj.options.add(new Option(ary1[1].toString(),ary1[0].toString()));
}
}
}
}
else
{
alert("sorry It has no data in database");
}
}
}
//delete values
function delValues(targetObject)
{
targetObject.innerHTML="";
}
function getZipCode(targerControl,originControl)
{
targerControl.value = originControl.value;
Panle_Hide(targerControl.Container.FloatContainer);
}
function selectZip()
{
// if(document.all["details"].style.visibility=="hidden")
// {
// document.all["details"].style.visibility="visible";
// }
// else
// {
// document.all["details"].style.visibility=="hidden";
// }
hiddenPanel();
}
function hiddenPanel()
{
document.getElementById("showPanel").style.display = "none";
}
function Zip_FloatPanel_Init()
{
for( var i = 0; i < Zip_Controls.length; i++ ) {
var info = Zip_Controls[ i ];
Zip_FloatPanel_Load( info );
}
}
function Zip_FloatPanel_Load( info )
{
var ZipCode = document.getElementById( info.ID );
var Container = document.getElementById( info.ContainerID );
var FloatContainer = document.getElementById( info.FloatContainerID );
var Text = document.getElementById( info.TextID );
var CodeText = document.getElementById( info.CodeTextID );
var Button = document.getElementById( info.ButtonID );
var GetButton = document.getElementById( info.GetButtonID );
var Country = document.getElementById( info.CountryID );
var State = document.getElementById( info.StateID );
var City = document.getElementById( info.CityID );
ZipCode.style.display = "";
Container.FloatContainer = FloatContainer;
Container.Text = Text;
Container.Button = Button;
FloatContainer.Container = Container;
Text.Container = Container;
Button.Container = Container;
FloatContainer.CodeText = CodeText;
FloatContainer.GetButton = GetButton;
FloatContainer.Country = Country;
FloatContainer.State = State;
FloatContainer.City = City;
CodeText.FloatContainer = FloatContainer;
GetButton.FloatContainer = FloatContainer;
Country.FloatContainer = FloatContainer;
State.FloatContainer = FloatContainer;
City.FloatContainer = FloatContainer;
FloatContainer.style.display = "none";
FloatContainer.style.position = "absolute";
FloatContainer.style.left = "0px";
FloatContainer.style.zIndex = 10000;
// showPanel.size = ( info.ListSize > List.options.length ) ? List.options.length : info.ListSize;
FloatContainer.multiple = false;
FloatContainer.IsShowing = false;
// FloatContainer.Show = Panle_Show;
// FloatContainer.Hide = Panle_Hide;
}
function Zip_Button_Toggle(button) {
if ( button.Container.FloatContainer.IsShowing == true ) {
// this.FloatContainer.Hide();
Panle_Hide(button.Container.FloatContainer)
} else {
Panle_Show(button.Container.FloatContainer);
}
}
function Panle_Show(floatContainer) {
if ( !floatContainer.IsShowing && !floatContainer.disabled ) {
// if ( typeof ( this.Container.Text.dataSrc ) != "undefined" ) { // to overcome misaligniment in IE
// this.style.top = ( this.Container.offsetHeight + 10 ) + "px";
// } else {
floatContainer.style.top = ( floatContainer.Container.offsetHeight ) + "px";
// }
// this.style.width = this.Container.offsetWidth + "px";
// this.style.width = "100px";
floatContainer.style.display = "";
floatContainer.focus();
floatContainer.IsShowing = true;
}
}
function Panle_Hide(floatContainer) {
if ( floatContainer.IsShowing ) {
floatContainer.style.display = "none";
floatContainer.IsShowing = false;
}
}
3、ZipCode.ashx(这里的逻辑可以根据自己的数据库结构来定),该页面是独立出来的,放在被引用的项目中,没有和自定义控件一起编译进去,这里是一个问题,有没有朋友解决一下把这个文件一起编译到 zip 的自定义控件中,这样一来就更方便了。
Code
1<%@ WebHandler Language="C#" Class="ZipCode" %>
2
3using System;
4using System.Web;
5using System.Text;
6using System.Data;
7using DBUtility;
8public class ZipCode : IHttpHandler
9{
10
11 public void ProcessRequest(HttpContext context)
12 {
13 context.Response.ContentType = "text/plain";
14 string id = context.Request["id"];//country id or state id or city id
15 string type = context.Request["type"];//0 means country;1 means state;2 means city
16 DataSet ds = new DataSet();
17 StringBuilder sb = new StringBuilder();
18 string str = "";
19 if (id != "" && type != "")
20 {
21 string groupName = "";
22 if (type == "1")
23 {
24 groupName = "State";
25 }
26 else if (type == "2")
27 {
28 groupName = "City";
29 }
30 if (type == "3")//get zip code by city
31 {
32 ds = SqlHelper.Query(SqlHelper.LocalSqlServer, "select * from Country_State_City_View where CaptionMessageID='" + id + "'");
33 //ds.ReadXml("City.xml");
34 if (ds != null)
35 {
36 if (ds.Tables[0].Rows.Count > 0)
37 {
38 //DataView dv = ds.Tables[0].DefaultView;
39 //dv.RowFilter = "CityID = " + id;
40 sb.Append(",");
41 sb.Append(ds.Tables[0].Rows[0]["CaptionMessage_JokerField_3"].ToString());
42 }
43 }
44 }
45 else
46 {
47 ds = SqlHelper.Query(SqlHelper.LocalSqlServer, "select * from Country_State_City_View where GroupName='" + groupName + "' and GroupFatherID='" + id + "'");
48 //ds.ReadXml("State.xml");
49 if (ds != null)
50 {
51 if (ds.Tables[0].Rows.Count > 0)
52 {
53 //DataView dv = ds.Tables[0].DefaultView;
54 //dv.RowFilter = "CountryID = " + id;
55 for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
56 {
57 sb.Append(",");
58 sb.Append(ds.Tables[0].Rows[i]["CaptionMessageID"].ToString());
59 sb.Append("|");
60 sb.Append(ds.Tables[0].Rows[i]["CaptionMessageSignName"].ToString());
61 }
62 }
63 }
64 }
65 }
66 str = (sb!=null?sb.ToString().Substring(1):"");
67 if (str != "")
68 {
69 context.Response.Write(str);
70 }
71 }
72
73 public bool IsReusable
74 {
75 get
76 {
77 return false;
78 }
79 }
80}
81
有一个问题需要大家帮忙,就是在国家、省市联动那一块,我用的是 ajax 来实现的,而没有用微软自带的 ICallbackEventHandler 功能来实现,原因是用 ICallbackEventHandler 来实现出现一个问题。就是在引用的页面代码里加 Response.Write() 功能时,该控件的联动不可用,代码就不贴出来了,以下有源码下载,请朋友帮忙.
源码:自定义控件(问题)