2009-10-30 103 views
6

有誰知道建立一個功能類似一個自定義的HtmlHelperextension方法的語法..Html.BeginForm()類型的擴展

<% using (Html.BeginForm()) {%> 

<p>Loads of html stuff here </p> 

<% } %> 

我沿着....

行思考的東西

任何想法?

乾杯,

ETFairfax

回答

8

你需要創建一個實現IDisposable接口和ret的類從你的HtmlHelper甕。

public static class HtmlHelperTableExtensions { 
    private class TableRenderer : IDisposable { 
     HtmlHelper html; 
     public TableRenderer(HtmlHelper html) { 
      this.html = html; 
     } 
     public void Dispose() { 
      HtmlHelperTableExtensions.EndTable(html); 
     } 
    } 
    public static IDisposable BeginTable(this HtmlHelper html) { 
     // print begin table here... 
     return new TableRenderer(html); 
    } 
    public static void EndTable(this HtmlHelper html) { 
     // print end table here... 
    } 
} 
+0

不錯的一個。謝謝Mehrdad – ETFairfax 2009-10-30 16:03:37

+3

只是爲了澄清這些閱讀此,你需要調用HttpContext.Current.Response.Write(「」);在Mehrdadhas寫的地方//在這裏打印開始表,//在這裏打印結束表。 – ETFairfax 2009-10-30 16:05:11

1

你需要有一個方法是這樣的:

public static IDisposable BeginTable(this HtmlHelper html, ...) 
{ 
    // write the start of the table here 

    return new EndTableWriter(); 
} 

EndTableWriter是這樣的:

private class EndTableWriter : IDisposable 
{ 
    public void Dispose() 
    { 
     // write the end of the table here 
    } 
}