使用内置助手的特定类的自定义Html助手

时间:2014-10-07 21:17:08

标签: model-view-controller html-helper

我无法绕过创建自定义html帮助程序,利用内置帮助程序渲染特定部分。 (想想复合助手。)此外,助手只对特定的类有用。

给出以下课程摘录

public class Notification {
   [Display("Notice")]
   public string Content { get; set; }
   public DateTime Created { get; set; }
   public bool RequiresAcknowledgement { get; set; }
}

我想渲染以下示例输出

<div class="notification">
   <!-- Notice that the DateTime property only displays the Date portion (i.e. Created.Date) -->
   <div class="notification-timestamp">Monday, October 07, 2014</div>
   <div class="notification-content">
      <h1>Notice</h1>
      This is a sample notice
   </div>
   <!-- This div is optional and only rendered if RequiresAcknowledgement == true -->
   <div class="notification-acknowledgement">
      <input type="checkbox">By clicking this you acknowledge that you have read the notice
   </div>
</div>

我认为我的扩展方法会有类似于

的签名
public static System.Web.Mvc.MvcHtmlString DisplayNotificationFor<TModel, TValue>(this System.Web.Mvc.HtmlHelper<TModel> helper, System.Linq.Expressions.Expression<Func<TModel, TValue>> expression)

但我不确定我是否需要TModel和/或TValue,因为我知道该方法仅适用于通知对象。

当我尝试执行以下操作时,该签名也会导致混淆

// is this the correct way to get my model??
var valueGetter = expression.Compile();
var model = valueGetter(helper.ViewData.Model) as Notification;

var timestamp = new System.Web.Mvc.TagBuilder("div");
timestamp.AddCssClass("notification-timestamp");

timestamp.InnerHtml = helper.DisplayFor(?????)      // What is the best way to output model.Created.Date?

// how about
// does not work/compile but shown as possible approach
timestamp.InnerHtml = new System.Web.Mvc.Html.DisplayExtensions.DisplayFor<Notification, TValue>(helper, n => n.Created.Date);

据我所知,上面显示的示例输出主要只是渲染只读文本,因此我可以直接渲染Notification对象的属性,而不是使用内置的辅助方法,但我问的问题可能是也适用于可编辑的表单。例如,允许创建和/或修改通知的表单。

我想重新使用现有助手的原因是他们已经支持根据数据类型呈现不同类型的输入(字符串vs bool vs DateTime vs email),它们支持验证属性,它们支持标签的Display属性等。

当然我想扩展我的简单示例,以允许自定义属性像特定id或其他css类一样传递。

我是否应该使用/创建自定义html帮助程序?

1 个答案:

答案 0 :(得分:0)

事实证明,限制表达式的类比我想象的要容易。

public static System.Web.Mvc.MvcHtmlString DisplayNotificationFor<TModel, TValue>(this System.Web.Mvc.HtmlHelper<TModel> helper, System.Linq.Expressions.Expression<Func<TModel, TValue>> expression)
   where TValue: Notification {

关键是附加到末尾的泛型约束。

这让我可以做到

@model Common.Notifications.Notification

@Html.DisplayNotificationFor(model => model)

// or

@model SomeViewModel

@Html.DisplayNotificationFor(model => model.ImportantNotification)

,而

@Html.DisplayNotificationFor(model => model.SomeStringProperty)

显示为设计时错误。

相关问题