Reputation: 2729
I have a MVC CRUD site that has a Date Approved Textbox. When the new entry is created it is stored properly as "dd-MM-yyyy" in the SQL Sever. When I want to update an entry the Date Required textbox contains the date AND 12:00:00AM . I'm guessing this is because SQL Server is a date datatype and .Net is a DateTime. Any idea how to get rid of the 12:00:00AM ?
Failed attempts...
I've tried adding it to my viewmodel
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage="Required")]
[DataType(DataType.Date)]
[Display(Name="Date Requested")]
public DateTime? Date_Requested { get; set; }
and also...
string test = Convert.ToDateTime(model.Date_Requested).ToString;
EDIT the html textbox
@Html.TextBoxFor(model => model.Date_Requested,new {@class="datepicker" })
EDIT JQuery DatePicker
$(".datepicker").datepicker({
onSelect: function () {
$(this).valid();
}
});
Upvotes: 0
Views: 110
Reputation: 152521
TextBoxFor
does not honor format attributes (not sure if this is intended or a bug). You can either use EditorFor
:
@Html.EditorFor(model => model.Date_Requested,new {@class="datepicker" })
or set the format in TextBoxFor
:
@Html.TextBoxFor(model => model.Date_Requested,
new {
@class="datepicker",
@Value = Model.Date_Requested.ToString("MM-dd-yyyy")
});
Upvotes: 1
Reputation: 271
Expanding on Jonesy answer from above.
public string DateRequestedShortDate
{
get
{
return Date_Requested == null ? "" : Date.Parse(Date_Requested).ToShortDateString();
}
}
Parse won't mess up the data being inserted into SQL , hope it helps.
Upvotes: 0
Reputation: 25370
you could add another property, using ToShortDateString:
public string DateRequestedShortDate
{
get
{
return Date_Requested == null ? "" : Date_Requested.ToShortDateString();
}
}
or simply set the textbox value to the ShortDateString to keep your binding
Upvotes: 2