自定义控件学习笔记(六)

自定义控件学习笔记(六)--生成回发

1。要点

1)生成回发的含义--不用用户点提交按钮,就自动提交表单
2)使用Page.ClientScript.GetPostBackEventReference(post)达到回发的目的

2。控件

using System;
using System.Web.UI;
using System.Collections.Specialized;


namespace TestCustomControl
... {
publicclassGenerateAutoPostBack:Control,IPostBackDataHandler
...{
boolautoPostBack=false;

publicstringText
...{
get
...{
if(ViewState["myText"]!=null)
...{
stringtext=(string)ViewState["myText"];
returntext;
}

else
...{
return"";
}


}

set...{ViewState["myText"]=value;}
}


publicboolAutoPostBack
...{
get...{returnautoPostBack;}
set...{autoPostBack=value;}
}


publiceventEventHandlerTextChanged;

protectedoverridevoidRender(HtmlTextWriterwriter)
...{
writer.WriteBeginTag(
"input");
writer.WriteAttribute(
"name",UniqueID);

if(ID!=null)
...{
writer.WriteAttribute(
"id",ClientID);
}


if(Text.Length>0)
...{
writer.WriteAttribute(
"value",Text);


}


if(autoPostBack)
...{
//writer.WriteAttribute("onchange","javascript:"+Page.GetPostBackEventReference(this));
PostBackOptionspost=newPostBackOptions(this);
writer.WriteAttribute(
"onchange","javascript:"+Page.ClientScript.GetPostBackEventReference(post));
}


writer.Write(HtmlTextWriter.TagRightChar);

writer.WriteEndTag(
"input");


}


publicboolLoadPostData(stringpostDataKey,NameValueCollectionpostCollection)
...{

//先用户修改文字并回传后,text被修改(Render)之前引发此事件。
//流程:render-》显示-》用户修改-》LoadPostData-》(RaisePostDataChangedEvent)-》Render(第二次)
stringtemp=Text;
Text
=postCollection[postDataKey];

if(temp!=Text)
returntrue;//引发RaisePostDataChangedEvent
else
returnfalse;
}


publicvoidRaisePostDataChangedEvent()
...{
if(TextChanged!=null)//指客户端使用控件时候,写入了(OnTextChanged="MethodName"),否则则认为用户没有处理此事件
...{
TextChanged(
this,newEventArgs());
}

}

}

}

3。用法

<% ... @PageLanguage="C#"AutoEventWireup="true"CodeFile="GeneratePostBack.aspx.cs"Inherits="TestCustomControl_First_GeneratePostBack" %>
<% ... @RegisterAssembly="GenerateAutoPostBack"Namespace="TestCustomControl"TagPrefix="Surance" %>
<! DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< html xmlns ="http://www.w3.org/1999/xhtml" >
< head runat ="server" >
< title > 无标题页 </ title >
</ head >
< body >
< form id ="form1" runat ="server" >
< div >
< Surance:GenerateAutoPostBack ID ="G1" Runat ="server" AutoPostBack ="true" OnTextChanged ="G1_OnTextChanged" />
</ div >
</ form >
</ body >
</ html >

后台

protected void G1_OnTextChanged( object sender,EventArgse)
... {
Response.Write(
"Generate");
}

你可能感兴趣的:(JavaScript,html,UI,Web,XHTML)