0

In one of our ASP.NET Core 1.1 project, I'm getting the following error when rendering following View. I think I'm correctly following suggestions from SO users like @DarinDimitrov here

Error: Input string was not in correct format

ViewModel:

Public Class OrdersViewModel
{
    ....
    [DisplayFormat(DataFormatString = "{(0:C)}")]
    public float? price { get; set; }
}

View:

@model MyProj.Models.OrdersViewModel
@{
Layout = "";
}
....
<tr>
    <td>Price:</td>
    <td>@Html.DisplayFor(t => t.price)</td>
</tr>

UPDATE:

This @String.Format("{0:c}", Model.price) works as suggested here by @nemesv. But I don't want to use it in the view since ModelView is used at multiple places on various views. So I would like to keep using DisplayFor(...) at those places instead - as it's a bit simpler.

nam
  • 21,967
  • 37
  • 158
  • 332

1 Answers1

0

System.FormatException that you have means that your DataFormatString is wrong. In your case you need to remove () from format string (explicit call of String.Format works as uses the different template):

[DisplayFormat(DataFormatString = "{0:C}")]
public float? price { get; set; }

If you need the result string to be like (123.45), not 123.45 then do

[DisplayFormat(DataFormatString = "({0:C})")]
Set
  • 47,577
  • 22
  • 132
  • 150