8

I am trying to use @HTML.DisplayFor in @ForEach statement but not successful.

The following is my existing code:

@foreach (var cost in Model.CustomerCost)
{
    <tr>
        <td>@cost .CustomerName</td>
        <td>@(cost.Cost!= 0 ? string.Format("{0:C}", cost.Cost) + " USD" : "-")</td>
    </tr>
}

However, i am trying to replace the following line of code

<td>@(cost.Cost!= 0 ? string.Format("{0:C}", cost.Cost) + " USD" : "-")</td>

with

@HTMLDisplayFor

<td>@(cost.Cost!= 0 ? Html.DisplayFor(model => model.CustomerCost[cost].Cost + "USD":"-")</td>

What is wrong in @HTML.DisplayFor syntax?

1 Answer 1

10

To access the Cost property of cost use

@(cost.Cost != 0 ? Html.DisplayFor(m => cost.Cost) + "USD":"-")

Side note: You may want to consider making property Cost nullable and using the DisplayFormat attribute on the property

[DisplayFormat(DataFormatString = "{0:C}USD", NullDisplayText = "-")]
public decimal? Cost { get; set; }

in which case you can simplify the view to just

@Html.DisplayFor(m => cost.Cost)

Note also the format you were using would be used in a for loop where cost is the indexer

for(int i = 0; i < Model.CustomerCost.Count; i++)
{
  @Html.DisplayFor(m => m.CustomerCost[i].Cost)
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, for your explanation. i understand it now. Also thanks for telling handling nullable using data annotation.
Just added another explanation FYI :)
Thanks Stephen Muecke :)
@Stephan, i used [DisplayFormat(DataFormatString = "{0:C0}", NullDisplayText = "-")] in my model and than <td>@Html.DisplayFor(m => cost.Cost)</td> ------ It shows 0 for nullable but not "-"... Any idea? I think in my case it is not null but 0.0 so NullDisplayText won't work here. Correct me if i am wrong?
The use of NullDisplayText is only applicable for a nullable type, so your property would need to be public decimal? Cost { get; set; } (or Nullable<decimal>) and the value of the property would need to be null. I only added that side note because I was a bit puzzled why you would display a zero value as "-" rather than "$0.00USD"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.