1
votes

I have set up a datepicker in a form using the following js:

$("#Expiry").datepicker({
   regional: 'en-GB',
   dateFormat: 'dd/mm/yy',
   firstDay: 1
});

and have the following in my view (asp.net MVC)

<%: Html.TextBoxFor(m => m.Expiry) %>

In my model, Expiry is a nullable DateTime?

When I use the datepicker to choose a date it does so with the correct format

When I load data from the database it always displays with 00:00:00 at the end for the time portion

How can I get it to not do this?

If I try to use a formatting expression in my binding then it won't compile.

Surely jQuery should respect the formatting I've specified for values that are pre-loaded into the form field?

It does apply the datepicker to the field, so I can choose with a calendar. It just doesn't apply the formatting to the loaded value

any ideas?

3
Shouldn't $("Expiry") be $("#Expiry")? - Sang Suantak
corrected - I thought the editor here added an 'S' which I deleted before posting- maybe it was some markdown or something? anyway - now corrected - ChrisCa
I faced the same problem. What i did was extract the date part using javascript's dateVal.substr(0,10) and set it when binding the textbox to the datepicker. Not an elegant solution, but got the job done. - Sang Suantak

3 Answers

6
votes

How can I get it to not do this?

You could decorate the corresponding DateTime property on your view model with the [DisplayFormat] attribute which allows you to specify a format:

public class MyViewModel
{
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Expiry { get; set; }

    ... other properties
}

and inside the view replace the TextBoxFor with an EditorFor call:

<%: Html.EditorFor(m => m.Expiry) %>
3
votes

Create an editor template ~/Views/Shared/EditorTemplates/DateTime.cshtml with following content:

@model DateTime?
@{
string finalDate = string.Empty;

if (Model != null)
{
    DateTime date = (DateTime)Model;
    finalDate = String.Format("{0:d}", date.Date.ToShortDateString());
}

@Html.TextBox(string.Empty, finalDate, new { @class = "datepicker" })

In your View write (sorry it's razor syntax, I don't know the aspx syntax)

@Html.EditorFor(model => model.Expiry)

So in future, you don't have to worry about date format in your application.

0
votes

If your application is going to have only one culture, you could set the culture in the web.config file like this:

<globalization culture="en-US" />

or for Spain:

<globalization culture="es-ES" />

This way, the binding will consider the specified format to convert the form input value.