2012-09-27 38 views
4

我知道在C#中我可以創建一個工廠,但我不知道如何在aspx中重用代碼。我的代碼最初只針對ARList,但現在有了IcnList。我想過要做一個switch語句,但是沒有更好的代碼呢?如何編碼重用apsx?

的功能

protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!Page.IsPostBack) 
      { 
       ARExtractionController arController = new ARExtractionController(); 
       Dictionary<int, string> ARDictionary = arController.GetTickets(); 
       List<int> sortedARList = new List<int>(); 
       foreach (KeyValuePair<int, string> kv in ARDictionary) 
       { 
        sortedARList.Add(kv.Key); 
       } 
       sortedARList.Sort(); 
       sortedARList.Reverse(); 
       ARList.DataSource = sortedARList; 
       ARList.DataBind(); 
       ARList.Items.Insert(0, " "); 
       ARList.AutoPostBack = true; 
      } 
     } 

enter image description here

+0

可能重複[如何重用此C#代碼?](http://stackoverflow.com/questions/6115926/how-to-reuse-this-c-sharp-code) – tomfanning

回答

2

在TicketExtractionWeb,創建一個BasePage類。

BasePage.cs:

public class BasePage : System.Web.UI.Page 
{ 
    // Add methods that are used on all your pages in here. 

    protected DateTime GetCurrentDate() 
    { 
     return DateTime.Now; 
    } 
} 

和頁面(我們稱之爲我的頁面):

public class MyPage : BasePage 
{ 
    protected Page_Load(object sender, EventArgs e) 
    { 
     var currentDate = this.GetCurrentDate(); 
    } 
} 

所以,當你創建另一個aspx頁面,則默認爲:

public class MyNewPage : System.Web.UI.Page 
{ 
    // ... 
} 

只需將: System.Web.UI.Page更改爲: BasePage

2

如果你只是希望能夠重用的代碼,添加一個類項目的實用方法,並在那裏傾倒了兩頁,使用。

如果您要重複使用代碼和關聯的用戶界面,請查看用戶控件(ascx文件),以便您可以做到這一點。

目前尚不清楚哪個適合您。

1

您應該能夠從一個頁面繼承以重用代碼。

頂aspx文件中:

<%@ Page Language="C#" AutoEventWireup="true" Inherits="MyNamespace.CommonCode" %> 
+0

你說的是技術上正確的,但我認爲這不太可能真正做到OP真正需要的東西。 – tomfanning

+2

@tomfanning技術上正確。最好的一種正確!哦,等一下,我明白你的意思了。 –

+0

除非你可以有多個Inherits屬性,當然! (我98%肯定你不能) – tomfanning