gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:22:44 25 4
gpt4 key购买 nike

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

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; }
}
}

我要
a) 以 14 000 € 格式显示
b) 以 14 000 € 格式编辑它

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

a) CustomModelBinder?应该为所有其余字段重写 Binder ,但我只需要预算
b) TypeConverter?
c) 数据类型(数据类型.货币)?似乎在编辑模式下不起作用(不显示为 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>

最佳答案

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

<input asp-for="Budget" asp-format="{0:C}" class="form-control" />

虽然发现这一点并不容易。 Input Tag Helper 中未提及介绍部分。最后通过ASP.NET Core MVC Input Tag Helper Deep Dive找到了

现在我明白了为什么人们说 ASP.NET Core 的文档缺乏 - 简介在一篇文章中用很长的篇幅解释了各种标签助手,解释了它们与 HTML 助手的关系,但是忽略了 Format 等重要属性。没有指向类文档的直接链接,需要进行一些挖掘才能找到它。

SO 中有很多类似的问题,答案是“你不能格式化”或提出自定义解决方案。

更新

issue于 2017 年 7 月开放,关于发布包含货币符号的货币值。该线程很有趣,因为它解释了 asp-format 仅影响显示,因此推荐的解决方案是将符号放在 input 之外,可能使用 Bootstrap 输入组:

The recommended solution here is to place the currency indicator outside of the editable field (e.g. before or after)

也许是这样的:

<div class="input-group">
<input asp-for="Budget" asp-format="{0:#,###.00}" class="form-control" />
<span class="input-group-addon">€</span>
</div>

关于c# - 在 ASP.NET MVC Core 中显示/编辑货币,为什么这么复杂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48205531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com