【问题标题】:Custom Model attribute for outputting html data- attributes用于输出 html 数据属性的自定义模型属性
【发布时间】:2017-08-10 21:26:33
【问题描述】:

我希望能够创建一个属性,例如[AttachDatePicker] 来装饰我的 ViewModel 日期时间属性,因此当我使用脚手架时,它会输出例如data-datepicker 作为我希望 datepicker 附加到的 html 元素的 html 属性。

我可以根据 microsoft 示例 here 执行此操作,但感觉不对,因为它与验证我需要的内容无关。

理想情况下,我希望避免创建自定义模板。有什么想法吗?

【问题讨论】:

标签: c# asp.net-core-mvc


【解决方案1】:

为什么不定义一个Editor Template 并使用[UIHint] 赋予DateTime 属性?

例如,创建 Views/Shared/EditorTemplates/Datepicker.cshtml

@model DateTime

@{
   IDictionary<string, object> htmlAttributes = new Dictionary<string, object>(); 
   // TODO: retrieve annotations from Model Metadata and add html attributes accordingly, e.g. "required"
   htmlAttributes.Add("data-datepicker", "");
}

<div class="@* TODO: set classes depending on your CSS framework *@">
    @Html.TextBox("", Model, htmlAttributes)
</div>

使用 [UIHint("{name of editor template}")] 为您的 ViewModel 分配属性

[Required] // example of an annotation you might want to handle
[UIHint("Datepicker")]
public DateTime SelectedDate { get; set; }

使用EditorFor 渲染属性,这将分派到正确的模板

@Html.EditorFor(m => m.SelectedDate) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 2016-01-03
    相关资源
    最近更新 更多