Reputation: 2748
I would like to differentiate a Date to a DateTime like :
public class ViewModel {
public Date Date { get; set; }
public DateTime DateTime { get; set; }
}
In my view, i would like call this :
@Html.EditorFor(p => Model.Date)
@Html.EditorFor(p => Model.DateTime)
to render :
<input data-val="true" data-rule-date="true" data-val-date="Must be a date." type="date" value="" aria-describedby="field-error"/>
<input data-val="true" data-rule-datetime="true" data-val-date="Must be a datetime." type="datetime" value="" aria-describedby="field-error"/>
The reason I want to do this, is to have 2 differents plugin initialisation and validation methods, using datepicker and jquery validate plugins, like :
<script type="text/javascript">
$.validator.addMethod("date", function(value, element) { [date validation code] });
$("[type='date']").datepicker({ format:"dd/MM/yyyy" });
$.validator.addMethod("datetime", function(value, element) { [time validation code] });
$("[type='datetime']").datetimepicker({ format:"dd/MM/yyyy HH:mm:ss" });
</script>
My question is : Am i obliged to declare a new struct Date
and his Html.EditorFor
implementation or there is a simpler way ?
Upvotes: 2
Views: 378
Reputation: 177
You can change what type this are represented as when rendered with the HTMLHelper by using System.ComponentModel.DataAnnotations
above the fields in your model
[DataType(DataType.Date)]
public DateTime Date { get; set; }
[DataType(DataType.DateTime)]
public DateTime DateTime { get; set; }
Upvotes: 1
Reputation: 9463
You can redirect to an EditorTemplate using an [UIHint]
attribute in the ViewModel. No Date
struct is needed.
public class ViewModel {
[UIHint("Date")]
public DateTime Date { get; set; }
public DateTime DateTime { get; set; }
}
With this declaration, @Html.EditorFor(m => m.Date)
will look for an EditorTemplate named Date.cshtml
and pass a DateTime
as model to this editor.
For more see: UIHint, DisplayTemplates, and EditorTemplates in MVC.
Upvotes: 1