ASP.NET MVC 3:TimeSpan 的 DisplayFormat 数据注释导致 FormatException

发布于 2025-01-07 04:05:04 字数 980 浏览 3 评论 0原文

在我的模型中,字段 Length 是一个带有以下数据注释的 TimeSpan:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{h\\:mm}")]

我根据建议使用了 <一个href="https://stackoverflow.com/questions/2869918/asp-net-mvc-2-html-textboxfor-best-way-to-specify-a-format-string-for-a-datetime">此处< /a>.我希望生成的文本框显示当前的长度值(以小时和分钟为单位)。

然而,在 MVC 3 中这似乎不再起作用,因为它会导致 FormatException。无论 Length 是否具有现有值,都会发生此异常。

Visual Studio 补充道,“将字符串转换为 DateTime 时,请先解析字符串以获取日期,然后再将每个变量放入 DateTime 对象中。”我什至不知道这意味着什么。我的变量是 TimeSpan,而不是字符串,那么为什么它首先尝试进行字符串转换呢?报告异常的对话框给出了一个死链接。

这是我认为的代码:

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

异常发生在 Html.EditorFor() 处。我不确定我在这里缺少什么,有人有什么建议吗?谢谢!

In my model, the field Length is a TimeSpan with the following Data Annotation:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{h\\:mm}")]

which I used per the suggestion here. I want the resulting textbox to display the current value for Length in hours and minutes.

However, in MVC 3 this doesn't seem to work anymore, because it causes a FormatException. This exception occurs whether or not Length has an existing value.

Visual Studio adds, "When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object." I don't even know what that means. My variable is a TimeSpan, not a string, so why is it attempting to do a string conversion in the first place? The dialog box reporting the exception gives a dead link.

This is the code in my view:

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

The exception occurs at Html.EditorFor(). I'm not sure what I'm missing here, does anyone have any suggestions? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

转身泪倾城 2025-01-14 04:05:04

您的格式说明符需要位置标识符:

{0:h\\:mm}

Your format specifier needs the position identifier:

{0:h\\:mm}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文