Hi.
I start study asp.net mvc with simple task. I want to use datetime edit template with bootstrap datetimepicker.
So, first step, EF Model:
[MetadataType(typeof(AEventMetaData))] public partial class AEvent { } public class AEventMetaData { [DataType(DataType.DateTime)] [DisplayFormat( DataFormatString="{0:dd.MM.yyyy HH:mm}", ApplyFormatInEditMode=true )] public Nullable<System.DateTime> eventDateFrom { get; set; } [DataType(DataType.DateTime)] [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy HH:mm}", ApplyFormatInEditMode = true)] public Nullable<System.DateTime> eventDateTo { get; set; } }
Step 2 – I create view – AEvent Create View by scaffold
<div class="form-group"> @Html.LabelFor(model => model.eventDateFrom, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.eventDateFrom) @*, new {htmlAttributes = new { @class = "form-control", @data_date_format="DD.MM.YYYY HH:mm" } })*@ @Html.ValidationMessageFor(model => model.eventDateFrom, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.eventDateTo, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.eventDateTo) @*, new { htmlAttributes = new { @class = "form-control datecontrol" } })*@ @Html.ValidationMessageFor(model => model.eventDateTo, "", new { @class = "text-danger" }) </div> </div>
Step 3 – them I go to write editor template:
@model DateTime? @{ @Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "form-control single-line datecontrol ", type = "text"}) }
Step 4 – I get and install
* Datetimepicker for Bootstrap v3
//! version : 3.1.3
*
https://github.com/Eonasdan/bootstrap-datetimepicker/
Step 5 – write js for datetimepicker:
$(".datecontrol").each(function () { $(this).datetimepicker({ language: 'en' }); });
So it’s working but I have the error: "The field eventDateFrom must be a date."
I think my template don’t back value, because if I rewrite my editor template like this, it’s work fine:
@model DateTime? @{ <input type="text" name="eventDateFrom" class="form-control single-line" id="datecontrol" /> }
I don’t understand why. what I do wrong? what I should to do? How I must write it with helpers?
Thanx for help.
Hi svfaust,
Thanks for your post.
Please try to change this:
svfaust
@model DateTime? @{ @Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "form-control single-line datecontrol ", type = "text"}) }
into:
@Html.TextBox("", Model.HasValue ? Model.Value.ToShortDateString() : String.Empty,new { @class = "form-control datecontrol", type = "date" })
More information:
#Adding Bootstrap and HTML 5 Datepicker Functionality to an MVC 5 Project
http://www.aubrett.com/InformationTechnology/WebDevelopment/MVC/DatePickerMVC5.aspx
and another similar thread:
Hope this can be helpful.
Best Regards,
Eileen