在Asp.Net开发时,用到的JS库、通用的CSS等,在许多页面都会用到,而每次都需要手动引入,相当麻烦,而且有时一旦忘了引用,还得找半天才能找到问题。那有没有什么办法能够一劳永逸的呢?答案是有的。
  我们知道Asp.Net是可以通过后台来渲染前端的,所以如果能够在渲染时将所要的js库和css等添入可以了。而为了能够复用,所以需要进行类的继承。我们写一个Page的基类PageBase,代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Text;
namespace AspNetLoadJsCss.Common
{
public class PageBase : System.Web.UI.Page
{
public static readonly string SCRIPT_INCLUDE_TEMPLATE = "<script src="{0}" type="text/javascript"></script> ";
public static readonly string STYLE_INCLUDE_TEMPLATE = " <link href="{0}" rel="stylesheet" type="text/css"/> ";
public static readonly string SCRIPT_CONTENT_TEMPLATE = "<script type="text/javascript">{0}</script> ";
protected void Page_InitComplete(object sender, EventArgs e)
{
LiteralControl viewportControl = new LiteralControl();
viewportControl.ID = "viewport";
viewportControl.Text = " <meta name="viewport" content="width=device-width, initial-scale=1" />";
this.Header.Controls.AddAt(GetNextControlIndex(this), viewportControl);
LiteralControl jqueryCssControl = new LiteralControl();
jqueryCssControl.ID = "/jquery.mobile-1.4.4.min.css";
jqueryCssControl.Text = String.Format(STYLE_INCLUDE_TEMPLATE, "/css/themes/default/jquery.mobile-1.4.4.min.css");
this.Header.Controls.AddAt(GetNextControlIndex(this), jqueryCssControl);
LiteralControl myCssControl = new LiteralControl();
myCssControl.ID = "/my.css";
myCssControl.Text = String.Format(STYLE_INCLUDE_TEMPLATE, "/css/my.css");
this.Header.Controls.AddAt(GetNextControlIndex(this),myCssControl);
String jsPath = "/js/jquery.js";
this.ClientScript.RegisterStartupScript(this.GetType(),
"jquery",
String.Format(SCRIPT_INCLUDE_TEMPLATE, jsPath),
false);
jsPath = "/js/jquery.mobile-1.4.4.min.js";
this.ClientScript.RegisterStartupScript(this.GetType(),
"jquery.mobile",
String.Format(SCRIPT_INCLUDE_TEMPLATE, jsPath),
false);
jsPath = "/js/default.js";
this.ClientScript.RegisterStartupScript(this.GetType(),
"default",
String.Format(SCRIPT_INCLUDE_TEMPLATE, jsPath),
false);
}
/// <summary>
/// 取得下一个控件的位置
/// </summary>
/// <returns></returns>
private static int GetNextControlIndex(Page page)
{
int index = 0;
// 如果存在自定义(以CONTROL_ID_PREFIX开头)的控件,则返回后一个自定义控件的下一个位置
// 如果不存在自定义的控件,则返回<title>的下一个位置
bool startControlBlock = false;
int titleIndex = 0;
String CONTROL_ID_PREFIX = "";
foreach (Control c in page.Header.Controls)
{
if (c is HtmlTitle)
{
titleIndex = index;
}
if (c.ID != null && c.ID.StartsWith(CONTROL_ID_PREFIX))
{
startControlBlock = true;
}
else
{
if (startControlBlock)
{
break;
}
}
index++;
}
int retIndex = startControlBlock ? index : titleIndex + 1;
if (retIndex < 0)
{
retIndex = 0;
}
else if (retIndex >= page.Header.Controls.Count)
{
retIndex = page.Header.Controls.Count - 1;
}
return retIndex;
}
protected virtual void Page_Load(object sender, EventArgs e)
{
}
}
}