【问题标题】:Format Exception in View MVC C#View MVC C#中的格式异常
【发布时间】:2015-05-16 16:24:51
【问题描述】:

以下是从我的视图模型中提取的 sn-p:

[Display(Name = "Time")]
    [Required(ErrorMessage = "Is required field. Format hh:mm (24 hour time)")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
    public Nullable<System.TimeSpan> EventPerformance_Time { get; set; }

这是来自我的 View.cshtml:

<div class="form-group">
            @Html.LabelFor(model => model.EventPerformance_Time, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.EventPerformance_Time, "{0:HH:mm}", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EventPerformance_Time, "", new { @class = "text-danger" })
            </div>
        </div>

当我运行项目时,我不断收到以下错误:

FormatException:输入字符串的格式不正确。

在@Html.EditorFor.....等行

我尝试了这么多不同的“解决方案”,但都没有奏效,我很困惑是哪里出了问题,因为在另一个视图模型中它工作得很好!

有什么帮助吗?非常感激。

【问题讨论】:

  • 就在我的脑海中,日期和时间的格式字符串中的分钟格式字符 n(如 HH:nn)不是。我认为 m 只是几个月。
  • 我一直在使用 m,它可以表示分钟。我认为要代表月份,它需要是 MM 而不是大写字母。但当然我可能是错的。

标签: c# asp.net-mvc exception format


【解决方案1】:

我会很高兴看到您的示例在哪里有效。你使用的是什么版本的 MVC?在EditExtension.EditorForEditorExtensions.EditorFor Methods 文档中,我没有看到支持您所用内容的方法签名。你能按照这些思路做点什么吗Html.TextBoxFor formatting or Html.EditorFor htmlAttributes?

【讨论】:

  • 我正在使用 MVC5,我展示的代码是在为控制器添加视图时自动生成的。我自己添加的唯一部分是“{0:HH:mm}”(我从另一个解决方案中获得)。至于它为我工作的其他部分,View.cshtml 与我上面显示的完全一样,与视图模型的唯一区别是我添加了额外的属性,但 EventPerformance_Time 部分也是相同的。编辑;我还尝试了您发布的链接中的格式,但仍然给我同样的错误。
【解决方案2】:

这种格式有效:“{0:hh:mm:ss}”

https://msdn.microsoft.com/en-us/library/ee372287%28v=vs.110%29.aspx

public class Test
{
    [Display(Name = "Time")]
    [Required(ErrorMessage = "Is required field. Format hh:mm (24 hour time)")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:hh\:mm\:ss}")]
    public Nullable<System.TimeSpan> EventPerformance_Time { get; set; }
}


<div>
@Html.LabelFor(m => m.EventPerformance_Time)
<div>
    @Html.EditorFor(m => m.EventPerformance_Time)
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多