Reputation: 1432
I have a model that contains a datetime field.
The column in the DB which it prepresents is of datatype 'date', so it has no time value.
The model date field is bound to a jquery-ui datepicker in my view.
When the page loads, it has time value: 1989/02/14 12:00:00 AM
How can I prevent the time value from being added?
Do I have to manually strip out the time portion with jQuery for every date field?
EDIT:
There is no point in editing the model, when the page loads its still there
Controller:
ClientModel c = DBContext.Clients.find(id);
//Doing any kind of date formatting here to c.DateOfBirth is ignored
return PartialView("_ClientDetailsView", c);
View:
@Html.TextBoxFor(model => model.DateOfBirth , new { @class = "date-field" })
I'm thinking that the solution would be something like a model attribute or a HtmlHelper parameter.
Upvotes: 2
Views: 2927
Reputation: 1432
Thanks for the help Henk
In the end I grew tired of trying to find a 'proper' solution so I wrote the following jquery function and calling it on each page as required.
function DropTimeSegments() {
$(".datepicker").each(function (index, item) {
$(item).val(FormatDate(new Date($(item).val())));
});
function FormatDate(Date) {
return Date.getFullYear() + '-' + pad(Date.getMonth(), 2) + '-' + pad(Date.getDate(), 2);
}
function pad(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
Upvotes: 1
Reputation: 46501
You can use the DataType
attribute for this. Decorate your DateOfBirth
property in the ClientModel
with it:
public class ClientModel
{
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
}
Also see the DataType
enum.
DisplayFormat
attribute if you the DataType
attribute doesn't fit your needs:
[DisplayFormat(DataFormatString = "dd MM, yyyy")]
public DateTime DateOfBirth { get; set; }
Upvotes: 2