ASP.NET MVC ViewModel mapping with custom formatting

て烟熏妆下的殇ゞ 提交于 2019-12-03 07:34:43

A custom TypeConverter is what you're looking for:

Mapper.CreateMap<string, decimal>().ConvertUsing<MoneyToDecimalConverter>();

Then create the converter:

public class MoneyToDecimalConverter : TypeConverter<string, decimal>
{
   protected override decimal ConvertCore(string source)
   {
      // magic here to convert from string to decimal
   }
}

Have you considered using an extension method to format money?

public static string ToMoney( this decimal source )
{
    return string.Format( "{0:c}", source );
}


<%= Model.CurrencyProperty.ToMoney() %>

Since this is clearly a view-related (not model-related) issue, I'd try to keep it in the view if at all possible. This basically moves it to an extension method on decimal, but the usage is in the view. You could also do an HtmlHelper extension:

public static string FormatMoney( this HtmlHelper helper, decimal amount )
{
    return string.Format( "{0:c}", amount );
}


<%= Html.FormatMoney( Model.CurrencyProperty ) %>

If you liked that style better. It is somewhat more View-related as it's an HtmlHelper extension.

Have you considered putting a DisplayFormat on your ViewModel? That is what I use and it's quick and simple.

ViewModel :
    [DisplayFormat(DataFormatString = "{0:c}", ApplyFormatInEditMode = true)]
    public decimal CurrencyProperty { get; set; }


View :
    @Html.DisplayFor(m => m.CurrencyProperty)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!