Csharp/C#教程:创建扩展方法以生成打开和关闭标记,如Html.BeginForm()分享


创建扩展方法以生成打开和关闭标记,如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属性

上述就是C#学习教程:创建扩展方法以生成打开和关闭标记,如Html.BeginForm()分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

Content Here

<% } %>

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/983235.html

(0)
上一篇 2021年12月19日
下一篇 2021年12月19日

精彩推荐