【问题标题】:C# data annotations for model's prop not formatted? - type double模型道具的 C# 数据注释未格式化? - 类型双
【发布时间】:2023-04-09 02:09:01
【问题描述】:

我有一个带有数据注释 [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)] 的类,它根本没有格式化。我的课堂上也包含了using System.ComponentModel.DataAnnotations;。

下面是我的课:

    public class StepTwo : IEnumerable
    {
        public int Id { get; set; }
        public string Party { get; set; }
        public string Currency { get; set; }

        [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
        public double? Amount { get; set; }

        public IEnumerator GetEnumerator()
        {
            return GetEnumerator();
        }
    }

现在当我在我的程序中使用这个类时,数字没有被格式化?我知道我可以在 Razor 页面中执行此操作,但使用数据注释的全部意义在于您不必在任何地方都执行此操作。

我试过[DisplayFormat(ApplyFormatInEditMode = true), DataFormatString = "{0:n2}"],但它没有改变任何东西。

我不确定为什么没有格式化?我错过了什么?

感谢您的帮助,感谢您的建议。

我在下面包含了相关的 Razor 页面:

<table class="table table-hover">
    @foreach (var cus in Model.SSTwo)
    {
        <tr>
            <td>@cus.Id</td>
            <td>@cus.Currency</td>
            <td>@cus.Party</td>
            <td>@cus.Amount</td>

        </tr>
    }
</table>

【问题讨论】:

  • 请附上您的剃须刀/查看代码
  • @jcruz,我已经添加进去了

标签: c# .net asp.net-core data-annotations


【解决方案1】:

您已设置 ApplyFormatInEditMode = true,因此格式化仅在编辑模式下有效,只需将其删除即可查看格式化工作。

【讨论】:

    【解决方案2】:

    试试这个:

    <table class="table table-hover">
    @foreach (var cus in Model.SSTwo)
    {
        <tr>
            <td>@cus.Id</td>
            <td>@cus.Currency</td>
            <td>@cus.Party</td>
            <td>@Html.DisplayFor(modelitem=>cus.Amount)</td>
        </tr>
    }
    </table>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      相关资源
      最近更新 更多