2009-10-30 13 views
6

¿Alguien sabe la sintaxis para crear un método HtmlHelperextension a medida que se comporta como ..Html.BeginForm() tipo de extensión

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

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

<% } %> 

Estoy pensando en algo en la línea de ....

¿Alguna idea?

Saludos,

ETFairfax

Respuesta

8

Usted necesita crear una clase que implemente IDisposable interfaz y ret llama eso desde tu 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

nice one. Gracias Mehrdad – ETFairfax

+3

Solo para aclarar a los que lean esto, deben llamar a HttpContext.Current.Response.Write (""); en los lugares que Mehrdad ha escrito // imprime la tabla de inicio aquí, y // imprime la tabla de finalización aquí. – ETFairfax

1

que había necesidad de contar con un método algo como esto:

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

    return new EndTableWriter(); 
} 

Cuando el EndTableWriter es algo como esto:

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