I'm working on a mvc5 project. A have generated a view containing following html/razor:
<div class="form-group">
@Html.LabelFor(model => model.Reservation.ReservationDate, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Reservation.ReservationDate)
@Html.ValidationMessageFor(model => model.Reservation.ReservationDate)
</div>
</div>
I made a EditorTemplate so I can use this datepicker:
@model DateTime?
<input id="@Html.IdForModel()" name="@Html.NameForModel()" value="@ViewData["Date"]" data-provide="datepicker" data-date-format="dd/mm/yyyy" data-date-autoclose="true" data-date-today-highlight="true" />
and included the template in my view:
@Html.EditorFor(model => model.Reservation.ReservationDate, new { Date = @Model.Reservation.ReservationDate})
The problem is, I lose the validation I defined via the data annotation in my model, because
class="text-box single-line valid" type="date" data-val-required="The Datum field is required." data-val-date="The field Datum must be a date." data-val="true"
gets overridden by the EditorTemplate. I could include that code in my template, but that way its hard-coded. For me, that's not a option.
So I was wondering, how can I add those html annotations in a better way?
This is the property from my model, with its DataAnnotions:
[UIHint("DatePicker")]
[DisplayName("Date")]
[DataType(DataType.Date, ErrorMessage="Not a valid date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]
public DateTime ReservationDate { get; set; }
You are creating a little extra work for yourself by creating the input HTML element instead of using Html.TextBoxFor(). Try doing this instead:
@Html.TextBoxFor(model => model, new { @class = "fieldDate", @Value = Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : "" })
In your javascript code:
$('.fieldDate').datepicker({
format: "dd/mm/yyyy",
autoclose: true,
todayHighlight: true
});
Also, does the jquery datepicker() method overwrite the HTML attributes?