Use ToString() with @Html.DisplayFor

戏子无情 提交于 2019-12-23 09:57:04

问题


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



来源:https://stackoverflow.com/questions/16598908/use-tostring-with-html-displayfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!