I have page that will show some currency data. I want to format the data with currency format but only using Display Template.
I have the following code:
@foreach (var item in Model.Data)
{
<tr class="@(item.Group%2==0? "odd-colore": "even-colore")">
<td>@Html.DisplayFor(modelItem => item.Name)</td>
<td>@Html.DisplayFor(modelItem => item.Amount1)</td>
<td>@Html.DisplayFor(modelItem => item.LName)</td>
<td>@Html.DisplayFor(modelItem => item.Amount2)</td>
<td>@Html.DisplayFor(modelItem => item.Amount3)</td>
</tr>
}
I have created a DisplayTemplate String.cshtml, since my datatype is string:
@model string
@{
IFormatProvider formatProvider = new System.Globalization.CultureInfo("en-US");
<span class="currency">@Model.ToString("C",formatProvider)</span>
}
But when I run it, I'm getting the error:
No overload for method 'ToString' takes 2 arguments
How can I display positive amount as $1000.00 and negative amount as ($1000.00) either using DisplayTemplate or string.Format("{0:C}")
The problem you're having is because you're trying to convert a
stringto a currency. From MSDN:The
.ToString(string format, IFormatProvider formatProvider)overload you're trying to use only exists for numeric types, which is why it's not compiling.As an example to demonstrate this:
So you have a couple of choices:
I believe 2 is the better option, because you're wanting to work with numeric data, so storing it as a string only adds complexity when it comes to calculating and formatting (as you can see here), as you're always going to have to perform conversions first.