Use ToString() with @Html.DisplayFor

2019-06-22 05:29发布

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

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

2条回答
Evening l夕情丶
2楼-- · 2019-06-22 05:35

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)
查看更多
The star\"
3楼-- · 2019-06-22 05:46

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

查看更多
登录 后发表回答