创建扩展方法以生成打开和关闭标记,如Html.BeginForm()

我想知道是否可以创建一个具有类似于Html.BeginForm()的function和行为的扩展方法,因为它会生成一个完整的Html标记,我可以在标记内具体说明它的内容。

例如,我可以有一个视图:

     

在我尝试使用此问题中的示例生成的function的上下文中,此function非常有用

这将使我能够为我将要的类型创建容器

   <% using(Html.BeginDiv(myType, tag) %>    

我意识到这会产生无效的XHTML,但我认为可能有其他好处超过这个,特别是因为这个项目不需要XHTMLvalidationW3C标准。

谢谢

戴夫

不太确定这对于简单地定义

元素有多大的价值,但事情就像这样

 ///  /// Represents a HTML div in an Mvc View ///  public class MvcDiv : IDisposable { private bool _disposed; private readonly ViewContext _viewContext; private readonly TextWriter _writer; ///  /// Initializes a new instance of the  class. ///  /// The view context. public MvcDiv(ViewContext viewContext) { if (viewContext == null) { throw new ArgumentNullException("viewContext"); } _viewContext = viewContext; _writer = viewContext.Writer; } ///  /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. ///  public void Dispose() { Dispose(true /* disposing */); GC.SuppressFinalize(this); } ///  /// Releases unmanaged and - optionally - managed resources ///  /// true to release both /// managed and unmanaged resources; false /// to release only unmanaged resources. protected virtual void Dispose(bool disposing) { if (!_disposed) { _disposed = true; _writer.Write(""); } } ///  /// Ends the div. ///  public void EndDiv() { Dispose(true); } } ///  /// HtmlHelper Extension methods for building a div ///  public static class DivExtensions { ///  /// Begins the div. ///  /// The HTML helper. ///  public static MvcDiv BeginDiv(this HtmlHelper htmlHelper) { // generates 
...
> return DivHelper(htmlHelper, null); } /// /// Begins the div. /// /// The HTML helper. /// The HTML attributes. /// public static MvcDiv BeginDiv(this HtmlHelper htmlHelper, IDictionary htmlAttributes) { // generates
...
> return DivHelper(htmlHelper, htmlAttributes); } /// /// Ends the div. /// /// The HTML helper. public static void EndDiv(this HtmlHelper htmlHelper) { htmlHelper.ViewContext.Writer.Write(""); } /// /// Helps build a html div element /// /// The HTML helper. /// The HTML attributes. /// private static MvcDiv DivHelper(this HtmlHelper htmlHelper, IDictionary htmlAttributes) { TagBuilder tagBuilder = new TagBuilder("div"); tagBuilder.MergeAttributes(htmlAttributes); htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag)); MvcDiv div = new MvcDiv(htmlHelper.ViewContext); return div; } }

并使用这样的

 <% using (Html.BeginDiv(new Dictionary{{"class","stripey"}})) { %> 

Content Here

<% } %>

将呈现

 

Content Here

或没有html属性

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

Content Here

<% } %>