Mark
Mark

Reputation: 7818

DateTime field failing validation with time included

My model has a DateTime field:

    [UIHint("DateTimeHHMM")]
    public DateTime TimeBooked { get; set; }

It is rendered using the EditorTemplate:

@model Nullable<System.DateTime> 

@if ( Model.HasValue ) { 
@Html.TextBox( "" , String.Format( "{0:dd/MM/yyyy HH:mm:ss}" , Model.Value ) , new  {     @class = "span3 disabled" } ) 
} 
else { 
@Html.TextBox( "" , String.Format( "{0:dd/MM/yyyy HH:mm:ss}" , DateTime.Now ) , new { @class = "span3 disabled" } ) 
} 

In my view, the syntax is:

    <div class="editor-label">
        @Html.LabelFor(model => model.TimeBooked)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.TimeBooked)
        @Html.ValidationMessageFor(model => model.TimeBooked)
    </div>

When creating a record in the view, when I click Save with the following in the text box:

22/07/2012 18:33:29

The field TimeBooked must be a date.

Is there something wrong with my Model or Editor Template?

Thank you,

Mark

Upvotes: 1

Views: 363

Answers (1)

Steen T&#248;ttrup
Steen T&#248;ttrup

Reputation: 3835

You should make sure the application is running in the proper language (CultureInfo), especially when it comes to date (and number) formats.

You can do this in the web.config file.

  <system.web>
    <globalization culture="en-GB" uiCulture="en-GB"/>

You should set this to whatever region/country that matches your needs, that way .NET will handle parsing dates and numbers properly.

Upvotes: 1

Related Questions