WebPart引用 .CSS 檔案與 .JS檔案

來源:互聯網
上載者:User

[原]WebPart引用.CSS 檔案與.JS檔案

 

昨天突然有個想法:WebPart能不能引用CSS檔案與JS檔案,然後上網找資料幾乎沒有看到這樣的資料,最終沒有解決;上網購的一本書《亮劍》昨天剛好到,早上沒事翻開一看,哎呀,印入我的眼帘了;給它寫出來跟大家分享一下,有不好的地方請指出;

在下面的代碼裡是非常的簡單的,這裡我並不是想展現My Code,而是講一個方法:

  1. 我們先定義兩個檔案,一個是.css檔案,一個是.js檔案,然後把它們都放在C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS\在這個目錄下在建立一個檔案夾codeArt,把這兩個檔案都放在這裡;

    我這兩個檔案的代碼如下:

    .CSS檔案

    相信大家這都看的懂了;

    .JS檔案

  2. 接下來就是WebPart的代碼怎麼來註冊這兩個檔案了;

代碼如下:

using System;

using System.Runtime.InteropServices;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Serialization;

 

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

using Microsoft.SharePoint.WebPartPages;

using System.Web.UI.HtmlControls;

 

namespace WebPart_CSS

{

[Guid("81236f7a-a38a-4744-a532-67ff6faca56b")]

public class WebPart_CSS : System.Web.UI.WebControls.WebParts.WebPart

{

public WebPart_CSS()

{

}

//聲明頁面等資源檔存放的目錄

public const string RESOURCE_PATH = "~/_layouts/codeArt/";

 

/// <summary>

/// 註冊CSS檔案

/// </summary>

/// <param name="filename">CSS檔案名稱</param>

public void RegisterCommonCSS(string cssFilename)

{

string id = cssFilename.ToLower().Replace(".", "_");

 

//判斷CSS檔案是否被添加過

foreach (Control ctl in this.Page.Header.Controls)

{

if (ctl.ID == id)

{

return;

}

}

 

//建立CSS檔案連結控制項

HtmlLink link1 = new HtmlLink();

link1.ID = id;

link1.Attributes["type"] = "text/css";

link1.Attributes["rel"] = "stylesheet";

link1.Attributes["href"] = base.ResolveUrl(RESOURCE_PATH) + cssFilename;

this.Page.Header.Controls.Add(link1);

}

/// <summary>

/// 註冊指令碼

/// </summary>

/// <param name="jsFilename">指令檔名稱</param>

public void RegisterCommonJS(string jsFilename)

{

//指令碼路徑

string jsPath = base.ResolveUrl(RESOURCE_PATH) + jsFilename;

//註冊指令碼

Page.ClientScript.RegisterClientScriptInclude(typeof(WebPart_CSS), jsFilename.ToLower(), jsPath);

}

protected override void OnPreRender(EventArgs e)

{

//註冊CSS檔案

RegisterCommonCSS("test.css");

//註冊JS檔案

RegisterCommonJS("test.js");

base.OnPreRender(e);

}

 

public Label lable = null;

protected override void CreateChildControls()

{

lable = new Label();

lable.Text = "我是張金山";

lable.CssClass = "fontCss";

this.Controls.Add(lable);

 

 

string strInnerHTML = "<input type='button' id='btnSearch' value='Search' onclick='javascript:testJS()'/>";

HtmlGenericControl html = new HtmlGenericControl();

html.InnerHtml = strInnerHTML;

this.Controls.Add(html);

}

}

}

 

這樣就可以了;部署後看下效果如下:

點擊按鈕如下:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.