I would like to be able to create an attribute eg [AttachDatePicker] to decorate my ViewModel datetime properties so when I use scaffolding it outputs eg data-datepicker as an html attribute for the html element I want the datepicker attached to.
I could do it based on the microsoft example here but it doesn't feel right as it is not related to validation what i need.
Ideally i would like to avoid creating custom templates. Any ideas?
Why not define an Editor Template and attribute the DateTime property with [UIHint]
?
For example, create 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>
Attribute your ViewModels using [UIHint("{name of editor template}")]
[Required] // example of an annotation you might want to handle
[UIHint("Datepicker")]
public DateTime SelectedDate { get; set; }
Render the property with EditorFor
, this will dispatch to the correct template
@Html.EditorFor(m => m.SelectedDate)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.