2013-02-19 45 views
1

我是有關於建立一個頁面的一些問題,動態我做的:重寫VerifyRenderingInServerForm上動態創建的網頁()

p = New Page(); 
Page myPage = new Page(); 
FormAtt ctrl = (FormAtt)myPage.LoadControl("path/to/my/file.ascx"); // here lies the gridview of evil 
myPage.Controls.Add(ctrl); 

問題是我收到

Control ... must be placed inside a form tag with runat=server 

好了,我已經發現我需要覆蓋VerifyRenderingInServerForm方法能夠調用一個無格式頁面,但我怎麼能覆蓋VerifyRenderingInServerForm因爲我沒有一個ASPX文件。


PS:我有一個相關的問題,我不知道該怎麼辦,因爲它們是不同的問題,但解決的辦法去同problema,我放棄了最後的解決方案 - 請參閱:Form is Null in Dynamically created Pages

+1

你可以嘗試創建一個已經覆蓋'VerifyRenderingInServerForm'的自定義'Page'。然後,而不是'p = New Page();'這個'p = New MyCustomPage();'。 – 2013-02-19 12:29:54

回答

3

您可以嘗試使用已覆蓋VerifyRenderingInServerForm自定義類:

public partial class MyCustomPage : System.Web.UI.Page 
{ 
    public override void VerifyRenderingInServerForm(Control control) 
    {   
    } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     var p = new MyCustomPage(); 
     FormAtt uc = (FormAtt)p.LoadControl("path/to/my/file.ascx"); 
     p.Controls.Add(uc); 
    } 
} 
+0

我認爲這是最好的方法,我試圖避免創建新類,因爲它只會用在我的方法中。 – Jonathan 2013-02-19 13:03:14

1

類似以前的問題。首先需要添加HtmlForm。 ASP.Net需要一個表單標籤來爲頁面添加控件。

Page myPage = new Page(); 
HtmlForm form = new HtmlForm(); 
FormAtt ctrl = (FormAtt)myPage.LoadControl("path/to/my/file.ascx"); 
form.Controls.Add(ctrl); 
myPage.Controls.Add(form); 
+0

這也起作用了,但是生成的HTML包含了一個不需要的表單 – Jonathan 2013-02-22 20:18:58