Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

c# - ASP.NET dynamically insert code into head

I'm working inside of a Web User Control (.ascx) that is going to be included in a regular web form (.aspx), but I need to be able to dynamically insert code into the head of the document from the User Control. In my Coldfusion days <cfhtmlhead> would do the trick. Is there an equivalent of this in ASP.NET or a similar hack?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To add HTML markup you can do the following:

In your UserControl's code you can access Page.Header, which is itself a control. To that control you can then add new controls:

HtmlGenericControl newControl = new HtmlGenericControl("someTag");
newControl.Attributes["someAttr"] = "some value";
Page.Header.Controls.Add(newControl);

To add script markup you don't need access to the head tag at all since ASP.NET has helper methods on the ClientScriptManager that do the work for you:

Here are examples of some code you can also put in your user control's code:

// Register some inline script:
Page.ClientScript.RegisterClientScriptBlock(GetType(), "myAlertScript", "alert('hello!')", true);

// Register a script reference:
Page.ClientScript.RegisterClientScriptInclude(GetType(), "myLibraryScript", "~/Scripts/MyScriptLibrary.js");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...