【问题标题】:DisplayFormat DataFormatString not working for decimal value in Razor ViewDisplayFormat DataFormatString 不适用于 Razor 视图中的十进制值
【发布时间】:2020-06-16 23:52:54
【问题描述】:

我有一个 asp.net core 3.1 mvc 网络应用程序。我有一个绑定到视图的模型。该模型具有可为空的十进制属性。我需要在视图中显示该属性。

这是引发错误的视图(左侧 DisplayFor):

 @Html.DisplayFor(model => model.Content)  @Html.DisplayFor(model => model.ContentUnits)

这是被绑定的属性:

[Display(Name = "Content")]
[DisplayFormat(DataFormatString = "{0:d}")]
[Range(0, 100)]
public decimal? Content { get; set; }
public string ContentUnits { get; set; }

使用调试器和即时窗口我可以看到该值为 0.0000400。这对我来说似乎是一个十进制数,所以我不明白为什么我的 DataFormatString 不起作用。它抛出的错误是:

FormatException:格式说明符无效。

【问题讨论】:

    标签: asp.net-mvc asp.net-core razor


    【解决方案1】:

    如果你想在视图中显示数据,这里有一个演示:

    控制器:

    [HttpGet]
        public ActionResult TestContent()
        {
            ContentModel contentModel = new ContentModel { Content =new decimal(0.0000400),ContentUnits= "ContentUnits" };
            return View(contentModel);
        }
    

    查看:

    @Html.DisplayFor(model => model.ContentUnits)
    <br>
    @Html.TextBox(" ", Model.Content)
    <br>
    @Model.Content
    <br>
    

    结果:

    【讨论】:

      猜你喜欢
      • 2011-12-12
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 2020-06-06
      • 1970-01-01
      • 2021-10-31
      相关资源
      最近更新 更多