Register JavaScript from within a UserControl in ASP.NET
I declare my javascript in the design page of a usercontrol (ascx). Is there a way to register this javascript block in the Head section? I don't want to use ClientScript.RegisterClientScriptBlock as I don't want to declare my开发者_C百科 javascript in the code-behind. I also cannot move it (entirely) into a separate file, because I use business logic to create it.
I would say that ClientScript.RegisterClientScriptBlock is the way to register scripts from user/custom controls. But as you don't want to put the script in code-behind, you can write the relevant code in ascx page inside server tags. For example,
<script runat="server">
protected override OnPreRender(sender as object, e as EventArgs)
{
base.onPreRender(sender, e);
string script;
// Logic to build the script goes here
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Key_" + this.ClientID, script, true);
}
</script>
精彩评论