Spiga

如何在 MOSS 網頁中使用 C# 程式碼

在使用 SharePoint Designer 2007 設計 MOSS 2007 的頁面 (.aspx) 時,如果要在頁面中加入 C# 程式碼,例如事件:

<%@ Page Language="C#" masterpagefile="~masterurl/default.master" title="未命名 1" inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" meta:progid="SharePoint.WebPartPage.Document" %>

<script type="text/c#" runat="server">

protected void Button1_Click(object sender, EventArgs e)
{
Button1.Text = DateTime.Now.ToString();
}
</script>

<asp:Content id="Content1" runat="server" contentplaceholderid="PlaceHolderMain">

<asp:Button ID="Button1" runat="server" Height="48px" onclick="Button1_Click"
Text="Button" Width="308px"/>

</asp:Content>

##ReadMore##

在執行時會出現以下錯誤訊息:
image

這是因為在預設的狀況下,MOSS 不允許在頁面中包含 <script> … </script> 的區塊,要解決這個問題,可以修改網站的 web.config 檔,一般是位於 c:\inetpub\wwwroot\wss\VirtualDirectories\80 資料夾下,也就是當初在建立應用程式時所設定的路徑,如下圖最下面的路徑:
image

在 web.config 中找到 <PageParserPaths> 區段,在裡面加入以下設定:

<PageParserPath VirtualPath="/Pages/*" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="true" />


image

  • VirtualPath="/Pages/*" : 設定 /Pages/ 路徑下的所有 .aspx 頁面都要進行程式碼解析。
  • CompilationMode="Always" : 設定每次都要編譯 .aspx 頁面。
  • AllowServerSideScript="true" : 設定 .aspx 頁面中允許出現 <script> … </script> 的程式碼區塊。
  • IncludeSubFolders="true" : 設定包含 VirtualPath 屬性以下的所有子目錄都有相同的設定。

這樣就可以允許在這個網站下的任何 .aspx 頁面中可以使用 <script> … </script> 的程式碼區塊,就可以撰寫 C# 程式碼了。

0 意見: