Model view controller 使用内置帮助程序的特定类的自定义Html帮助程序

Model view controller 使用内置帮助程序的特定类的自定义Html帮助程序,model-view-controller,html-helper,Model View Controller,Html Helper,我在创建自定义html帮助程序时遇到了麻烦,该帮助程序利用内置的帮助程序来呈现特定的部分。(想想复合助手。)此外,助手仅对特定类有用 给出下面的课堂摘录 public class Notification { [Display("Notice")] public string Content { get; set; } public DateTime Created { get; set; } public bool RequiresAcknowledgement { g

我在创建自定义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>
我知道上面显示的示例输出主要只是呈现只读文本,因此我可以直接呈现通知对象的属性,而不是使用内置的帮助器方法,但我要问的问题也可以应用于可编辑表单。例如,允许创建和/或修改通知的表单

我之所以想重用现有帮助程序,是因为它们已经支持根据数据类型呈现不同类型的输入(字符串vs bool vs DateTime vs email),它们支持验证属性,它们支持标签的显示属性,等等

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


在如何使用/创建自定义html帮助程序方面,我是否偏离了基准?

结果表明,限制表达式的类比我想象的要容易

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 {
鉴于

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

显示为设计时错误。

如果是针对特定类的,则可以将实例传递给参数,如
public static MvcHtmlString DisplayNotificationFor(HtmlHelper,通知)
但是为什么不为
Notification.cs
创建一个
显示模板呢?@StephenMuecke--我不能使用显示模板,因为我试图创建一个可以跨项目使用的库项目(即多个MVC应用程序)。据我所知,显示/编辑器模板(如局部视图)仅在定义它们的MVC应用程序中可用。我错了吗?不确定将模板复制到
视图/Shared/DisplayTemplates
比添加对库的引用和更新web.config文件更困难,但是我将使用html助手简短地发布一个答案如果库中只包含了助手扩展,那么是的……这与创建一个显示模板,然后将其从web项目复制到web项目是一样的。但是,该库还包含包含通知对象的类,以及用于将数据读/写到其源的接口和服务实现。此外,该库还变成了一个NuGet包,可在内部NuGet存储库中使用。出于所有这些原因,助手扩展是更好的选择。正如我在回答中所述,您可以使用内置的助手
System.Web.Mvc.Html.InputExtensions.CheckBox(…)
.CheckBoxFor(…)
。我刚刚根据您发布的示例输出创建了helper(其中只包含一个未绑定到任何属性的复选框,这有什么意义!)如果您的示例使用了现有扩展,我深表歉意……我读了不止一次,但显然没有读到。我可以发誓,这是只使用TagBuilder编写的代码,您可以显式地添加属性等等。但我想我错了。
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)