在ASP.NET MVC Core中显示/编辑货币,为什么这么复杂?

Ser*_*rge 3 c# asp.net-core asp.net-core-tag-helpers

在ASP.NET Core 2.0应用程序中,我有一个Foo包含许多经典字符串或数字成员以及int? Budget字段的类.

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace MyProj.ViewModels {
    public class RecordEditViewModel {
        public RecordEditViewModel() { }

        public string Name { get; set; }
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public string Prop3 { get; set; }
        public string Prop4 { get; set; }    
        public string Prop5 { get; set; }

        /// <summary>The project budget</summary>        
        //[Range(0, int.MaxValue, ErrorMessage = "Must be a positive number")]
        [Display(Name = "Budget REVM"), 
         DataType(DataType.Currency), 
         DisplayFormat(NullDisplayText = "-", 
                       ApplyFormatInEditMode = true, 
                       DataFormatString = "{0:C}")]
        public int? Budget { get; set; }

        public string Prop6 { get; set; }
        public string Prop7 { get; set; }
        public string Prop8 { get; set; }
        public DateTime CreatedOn { get; set; }    
        public string Prop9 { get; set; }
        public string Prop10 { get; set; }        
        public string Prop11 { get; set; }    
        [Display(Name = "Attachments"), UIHint("IFromFile")]
        public IEnumerable<IFormFile> Attachments { get; set; }
        public string Id { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想
一)在其显示14 000 €格式
二)在编辑14 000 €格式

这是一种典型的行为,以货币格式显示/编辑货币,但似乎很难在最新的Microsoft .NET Framework中实现.

a)CustomModelBinder?应该为所有其他字段重写一个活页夹,但我只需要预算
b)TypeConverter
c)DataType(DataType.Currency)?似乎不能在编辑模式下工作(不显示为int?)

我的看法:

<div class="col-md-6">
    <label asp-for="Budget" class="control-label"></label>
    <div>
        <input asp-for="Budget" class="form-control" />
        <span asp-validation-for="Budget" class="text-danger"></span>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Pan*_*vos 6

我注意到InputTagHelper有一个Format属性,这意味着可以写:

<input asp-for="Budget" asp-format="{0:C}" class="form-control" />
Run Code Online (Sandbox Code Playgroud)

发现虽然并不容易.在介绍的输入标记助手部分中没有提到它.最后,我通过ASP.NET Core MVC Input Tag Helper Deep Dive找到了它

现在我明白了为什么人们说缺乏ASP.NET Core的文档 - 介绍了在一篇文章中解释各种标记帮助器的长篇大论,解释了它们与HTML Helpers的关系,但是省略了重要的属性,如Format.如果没有直接链接到类的文档,需要花一点时间才能找到它.

在SO中有相当多的类似问题,答案是"你无法格式化"或提出自定义解决方案.

UPDATE

2017年7月开设了一个关于发布包含货币符号的货币值的问题.线程是有趣的,因为它解释了asp-format只影响显示,所以建议的解决方案是将符号放在input可能使用Bootstrap输入组之外:

这里推荐的解决方案是将货币指标放在可编辑字段之外(例如之前或之后)

也许是这样的:

<div class="input-group">
    <input asp-for="Budget" asp-format="{0:#,###.00}" class="form-control" />
    <span class="input-group-addon">€</span>
</div>
Run Code Online (Sandbox Code Playgroud)