asp.net – Razor base type / Templated Razor使用“using”关键字代理

前端之家收集整理的这篇文章主要介绍了asp.net – Razor base type / Templated Razor使用“using”关键字代理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前有一个div容器,用于表单中的所有输入字段,类似于:
  1. <div class="ux-single-field ui-widget-content ui-corner-all">
  2. @Html.LabelFor(m => m.Name)
  3. @Html.TextBoxFor(m => m.Name)
  4. </div>

我想知道如何使用templated razor delegate(或any other trick)封装它,所以就像我们使用:

  1. @using (Html.BeginForm()) {
  2. }

我可以简单地包装我的元素:

  1. @using (Html.ContentField()) {
  2. @Html.LabelFor(m => m.Name)
  3. @Html.TextBoxFor(m => m.Name)
  4. }

解决方法

使用Razor View引擎,这是有效的:
  1. namespace MyProject.Web.Helpers.Extensions
  2. {
  3. public static class LayoutExtensions
  4. {
  5. public static ContentField BeginContentField(this HtmlHelper htmlHelper)
  6. {
  7. return FormHelper(htmlHelper,new RouteValueDictionary());
  8. }
  9.  
  10. public static ContentField BeginContentField(this HtmlHelper htmlHelper,RouteValueDictionary htmlAttributes)
  11. {
  12. return FormHelper(htmlHelper,htmlAttributes);
  13. }
  14.  
  15. public static void EndContentField(this HtmlHelper htmlHelper)
  16. {
  17. htmlHelper.ViewContext.Writer.Write("</div>");
  18. }
  19.  
  20. private static ContentField FormHelper(this HtmlHelper htmlHelper,IDictionary<string,object> htmlAttributes)
  21. {
  22. TagBuilder tagBuilder = new TagBuilder("div");
  23. tagBuilder.MergeAttributes(htmlAttributes);
  24. tagBuilder.MergeAttribute("class","ux-single-field ui-widget-content ui-corner-all");
  25.  
  26. htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));
  27. return new ContentField(htmlHelper.ViewContext.Writer);
  28. }
  29. }
  30.  
  31. public class ContentField : IDisposable
  32. {
  33. private bool _disposed;
  34. private readonly TextWriter _writer;
  35.  
  36. public ContentField(TextWriter writer)
  37. {
  38. if (writer == null)
  39. throw new ArgumentNullException("writer");
  40.  
  41. _writer = writer;
  42. }
  43.  
  44. [SuppressMessage("Microsoft.Security","CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
  45. public void Dispose()
  46. {
  47. Dispose(true /* disposing */);
  48. GC.SuppressFinalize(this);
  49. }
  50.  
  51. protected virtual void Dispose(bool disposing)
  52. {
  53. if (!_disposed)
  54. {
  55. _disposed = true;
  56.  
  57. _writer.Write("</div>");
  58. }
  59. }
  60.  
  61. public void EndForm()
  62. {
  63. Dispose(true);
  64. }
  65. }
  66. }

仅供参考:使用旧的ASPX引擎,here’s how to do it.

猜你在找的asp.Net相关文章