如何使用后台代码在head标记中动态生成javascript?
利用c#后台注册js的技术大家都快用烂了,但是有时候我们想把js脚本添加到head中而不是在body中,怎么办呢?
.net framework2.0为我们提供了一些便利,大家可以尝试使用一下HtmlHead,这个东东正是我们所需要的.
主意我用的是HtmlHead.InnerHtml,有其他的属性自己可以试试,另外HtmlTitle和HtmlMeta也是2.0里的新东西,好多时候可以为我们后台控制提供方便.
.net framework2.0为我们提供了一些便利,大家可以尝试使用一下HtmlHead,这个东东正是我们所需要的.
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12public partial class Default2 : System.Web.UI.Page
13{
14 protected void Page_Load(object sender, EventArgs e)
15 {
16 string script = @"<script language='javascript' type='text/javascript'>document.write('this client script is created by back end code, and it is placed in head tag!')</script>";
17 HtmlHead header = Page.Header;
18 header.InnerHtml = script;
19 }
20}
21
查看一下客户端代码都什么东东:2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12public partial class Default2 : System.Web.UI.Page
13{
14 protected void Page_Load(object sender, EventArgs e)
15 {
16 string script = @"<script language='javascript' type='text/javascript'>document.write('this client script is created by back end code, and it is placed in head tag!')</script>";
17 HtmlHead header = Page.Header;
18 header.InnerHtml = script;
19 }
20}
21
主意我用的是HtmlHead.InnerHtml,有其他的属性自己可以试试,另外HtmlTitle和HtmlMeta也是2.0里的新东西,好多时候可以为我们后台控制提供方便.