ViewModel上的数据驱动货币代码

时间:2017-11-22 10:22:11

标签: c# asp.net-mvc

我在ASP.Net MVC 5中工作。我有以下ViewModel:

[Display(Name = "Shipping Cost")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#.#}")]
public decimal ShippingCost { get; set; }
[Display(Name = "Shipping Currency")]
public Currency ShippingCurrency { get; set; }

ShippingCurrency是一个看起来像这样的枚举:

public enum Currency
{
    GBP,
    USD,
    CAD,
    AUD
}

当我查看ViewModel的详细信息时,我希望看到附近有相关货币符号的运费,但我想从我的ViewModel而不是Razor视图中执行此操作。所以在View中,我想看到:

200 GBP
180 USD
320 CAD

有没有办法通过ViewModel上的数据属性获取该格式?

1 个答案:

答案 0 :(得分:2)

您不能使用Attribute,因为属性是元数据,必须在编译时知道。

相反,您可以在视图模型中包含只读属性以返回格式化值,例如

public string FormattedAmount
{
    get { return string.Format("{0:#.#} {1}", ShippingCost, ShippingCurrency); }
}

并在视图中

<span>@Model.FormattedAmount</span>

或者,您可以在视图

中组合两个属性的值
<span>@DisplayFor(m => m.ShippingCost)</span><span>@Model.ShippingCurrency </span>