`
txf2004
  • 浏览: 6866584 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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

阅读更多

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

1。要点

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

2。控件

usingSystem;
usingSystem.Web.UI;
usingSystem.Collections.Specialized;


namespaceTestCustomControl
...{
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">

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

后台

protectedvoidG1_OnTextChanged(objectsender,EventArgse)
...{
Response.Write(
"Generate");
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics