ASP.NET MVC 3:TimeSpan 的 DisplayFormat 数据注释导致 FormatException
在我的模型中,字段 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的格式说明符需要位置标识符:
Your format specifier needs the position identifier: