如何在Html.TextBoxFor中格式化DateTimeOffset? [英] How to format DateTimeOffset in Html.TextBoxFor?

查看:140
本文介绍了如何在Html.TextBoxFor中格式化DateTimeOffset?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Bootstrap 3和ASP.NET MVC 5上构建了一个用于编辑用户配置文件信息的视图,但是该视图在表单上以错误的格式显示.

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.

数据库是Neo4j,我正在使用Neo4jClient与.NET中的数据库进行交互. Neo4jClient要求使用DateTimeOffset对象而不是DateTime对象,才能使用Json.NET的序列化器传递给Neo4j的REST接口.因此,我的模型使用DateTimeOffset对象存储用户的生日.

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

我尝试在model属性上使用DataFormatString批注,但它仍无法以正确的格式显示:

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; }

此注释是否仍适用于DateTimeOffset对象?如何修复字符串格式?

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

推荐答案

在这里回答: https://stackoverflow.com/a/6140014/211747

摘要:TextBoxFor不尊重DataFormatString,您需要使用EditorFor,但是它不支持自定义HTML属性,因此您需要编辑器模板(Views\Shared\EditorTemplates\DateTimeOffset.cshtml).

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

这篇关于如何在Html.TextBoxFor中格式化DateTimeOffset?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆