2013-05-28 26 views
0

我有一個ASP.NET網站,而不是Web應用程序,我已經建立了一個自定義CompareValidator這是能夠獲得它自己的命名容器的外面的:如何讓自定義控件可用於ASP.NET網站?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI.WebControls; 
using System.Web.UI; 

public class GlobalCompareValidator : CompareValidator 
{ 
    new protected void CheckControlValidationProperty(string name, string propertyName) 
    { 
     Control control = this.Page.NamingContainer.FindControl(name); 
     if (control == null) 
     { 
      throw new HttpException("Validator_control_not_found"); 
     } 
     if (BaseValidator.GetValidationProperty(control) == null) 
     { 
      throw new HttpException("Validator_bad_control_type"); 
     } 
    } 
} 

和存在於App_Code目錄代碼。現在,我想用這個新的自定義控制的ASCX頁面上是這樣的:

<me:GlobalCompareValidator ID="compareValidator" CssClass="errorMessage" Display="None" 
    EnableClientScript="false" Text="&nbsp;" ValidationGroup="LHError" runat="server" /> 

然而,試圖註冊的組件時使用它:

<%@ Register TagPrefix="me" Namespace="MyNamespace" Assembly="MyAssembly" %> 

我得到這個錯誤:

Could not load file or assembly '...' or one of its dependencies. The system cannot find the file specified.

現在,這並不是真的那麼令人驚訝,因爲ASP.NET網站並沒有真正生成這樣的程序集。但是,如果我將Assembly標籤關閉,則無法找到GlobalCompareValidator。當然,它也可能找不到Assembly標籤,但是這個錯誤很可能隱藏在找不到組件的事實中。

如何在世界中獲得可用於ASP.NET網站的自定義控件?

回答

1

好了,解決這個問題是錯綜複雜的,但在這裏不言而喻。首先,在花費大量時間試圖讓自定義控件工作之後,我決定改變我對這個問題的思考方式。我說:

What if I could get the control in the right naming container instead?

似乎挺直的!在運行時,我們將從用戶控件中刪除控件並將其添加到用戶控件的父級控件。但是,這比看起來更復雜。您可以修改InitLoad中的Controls集合,這對於這個想法有點問題。但是,唉,堆棧溢出來救援by way of the answer here!因此,與武裝我下面的代碼添加到用戶控件:

protected void Page_Init(object sender, EventArgs e) 
{ 
    this.Page.Init += PageInit; 
} 

protected void PageInit(object sender, EventArgs e) 
{ 
    if (!string.IsNullOrEmpty(this.ControlToCompare)) 
    { 
     this.Controls.Remove(this.compareValidator); 
     this.Parent.Controls.Add(this.compareValidator); 
    } 
} 

你這裏是什麼在頁面生命週期的一個小漏洞。雖然我無法修改InitLoad中的Controls集合,但我可以在這兩個事件之間修改它!謝謝蒂姆!

這可以完成這項任務,因爲我可以在運行時將CompareValidator移動到適當的命名容器中,以便它可以找到它正在驗證的用戶控件。

注意:您還必須將ValidationProperty屬性粘貼到要比較您的值的用戶控件上。我這樣做是這樣的:

[ValidationProperty("Value")] 

然後當然有一個名爲Value是對用戶的控制公開的屬性。在我的情況下,該屬性繼承了相同的用戶控件,因此我正在修改CompareValidator,因爲我正在比較來自同一用戶控件的兩個值。

我希望這可以幫助別人!

1

可以使用Register指令有兩個目的:

  1. 包括用戶控件
  2. 包括自定義控制

如果你包括用戶控件時,才需要SRC屬性。就你而言,你使用的是自定義控件,所以你只需要命名空間和Assembly屬性。

可以爲更多信息,請這個MSDN頁:

http://msdn.microsoft.com/en-us/library/c76dd5k1(v=vs.71).aspx