ASP.NET动态插入code到头部 [英] ASP.NET dynamically insert code into head

查看:142
本文介绍了ASP.NET动态插入code到头部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个Web用户控件内部的工作(的.ascx),它会被包含在一个普通的web窗体(.aspx),但我需要能够动态插入code到头部从用户控制该文档。在我的ColdFusion的日子< cfhtmlhead>会做的伎俩。是否有这个在ASP.NET同等或类似的黑客?

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?

推荐答案

要添加HTML标记,你可以做到以下几点:

To add HTML markup you can do the following:

在你的用户控件的code,您可以访问Page.Header,这本身就是一种控制。为了该控件可以再加入新的控件:

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);

要添加脚本标记你不需要访问head标签,因为在所有ASP.NET对<一个辅助方法href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx\">ClientScriptManager为你做的工作:

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:

下面是一些$ C $的例子c您也可以把你的用户控件的code:

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");

这篇关于ASP.NET动态插入code到头部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆