Loading

在DetailsView的CommandField控件中注册javascript

在asp.net的DetailsView自定义javascript验证的时候,碰到了比较头疼的问题,折腾了许久。

给解决方案吧。

首先设置DetailsView的CommandField控件类型为ButtonType="Button"

<asp:CommandField ButtonType="Button" ShowInsertButton="True" />

后台代码为 CommandField注册脚本

private void RegisterCommandFieldJS()
{
bool registered = false;
foreach (Control ctrl in DetailsView1.Controls)
{

RegisteJS(ctrl,
ref registered);

if (registered)
{
return;
}

IterateChildControl(ctrl,
ref registered);
}
}

private void RegisteJS(Control ctrl, ref bool registered)
{
IButtonControl btn
= ctrl as IButtonControl;

if (btn != null)
{

if (btn.CommandName == "Insert")
{
string js = ClientScript.GetPostBackEventReference(
new PostBackOptions(ctrl, "", "", false, true, false, false, true, ""))
+ ";return (Page_IsValid && confirm('Are you sure to continue?'));";

((WebControl)ctrl).Attributes.Add(
"onClick", js);
((WebControl)ctrl).ToolTip
= "Click here to Insert";

registered
= true;
return;
}

}

}


private void IterateChildControl(Control ctrol, ref bool registered)
{
foreach (Control ctrl in ctrol.Controls)
{

RegisteJS(ctrl,
ref registered);

if (registered)
{
return;
}

IterateChildControl(ctrl,
ref registered);
}
}

protected void DetailsView1_DataBound(object sender, EventArgs e)
{
RegisterCommandFieldJS();
}

其中,

string js = ClientScript.GetPostBackEventReference(
new PostBackOptions(ctrl, "", "", false, true, false, false, true, ""))
+ ";return (Page_IsValid && confirm('Are you sure to continue?'));";

为RequiredFieldValidator等验证控件的注册代码

参考:

Adding Javascript to ANY CommandField control

posted @ 2011-02-15 20:42  .net's  阅读(696)  评论(0)    收藏  举报