Search code examples
c#twitter-bootstrap-3data-annotationsasp.net-mvc-5neo4jclient

How to format DateTimeOffset in Html.TextBoxFor?


I have a view built on Bootstrap 3 and ASP.NET MVC 5 for editing user profile information, but it displays in the incorrect format on the form.

The database is Neo4j and I'm using Neo4jClient to interact with the database from .NET. Neo4jClient requires the use of DateTimeOffset objects instead of DateTime objects to use Json.NET's serializer for passing to Neo4j's REST interface. Therefore, my model uses a DateTimeOffset object to store the birthday for a user.

Here is my form field in my view:

<div class="form-group">
    <label class="col-md-4 control-label" for="Birthday">Birthday</label>
    <div class="col-md-4">
        @Html.TextBoxFor(model => model.Birthday, new { @class = "form-control input-md datepicker", placeholder = "Birthday" })
        <span class="help-block">Please enter your birthday</span>
    </div>
</div>

The date has the following format when printed to the form:

M/dd/yyyy hh:mm:ss t -zzz

However, it should have this format since we just need the date part:

MM/dd/yyyy

I have tried using the DataFormatString annotation on the model property, but it still doesn't display in the correct format:

[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTimeOffset Birthday { get; set; }

Does this annotation still apply for DateTimeOffset objects? How do I fix the string formatting?


Solution

  • Answered here: https://stackoverflow.com/a/6140014/211747

    Summary: TextBoxFor doesn't respect DataFormatString, you need to use EditorFor, but that doesn't support custom HTML attributes, so you need an editor template (Views\Shared\EditorTemplates\DateTimeOffset.cshtml).