Use ToString() with @Html.DisplayFor

2019-06-22 05:41发布

问题:

Why can't I use ToString("#.##") with a @Html.DisplayFor such as:

@Html.DisplayFor(modelItem => modelItem.Balance.ToString("#.##"))

回答1:

when I've encountered this before, I simply added a Getter to the model that the View consumes.

public string FormattedBalance
{
    get
    {
        return this.Balance.ToString("#.##");
    }
}

And then just use it in your view:

@Html.DisplayFor(ModelItem => ModelItem.FormattedBalance)


回答2:

The DisplayFor renders the default ToString method for the supplied model property.

You can achieve what you want by writing your own @helper.

See http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx