How to format DateTimeOffset in Html.TextBoxFor?

筅森魡賤 提交于 2019-12-10 17:07:23

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/21864964/how-to-format-datetimeoffset-in-html-textboxfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!