Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ToString() with @Html.DisplayFor

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

@Html.DisplayFor(modelItem => modelItem.Balance.ToString("#.##"))
like image 244
rikket Avatar asked May 16 '13 23:05

rikket


People also ask

What is displayfor in mvchtmlstring?

Html.DisplayFor() The DisplayFor()helper method is a strongly typed extension method. It generates a html string for the model object property specified using a lambda expression. DisplayFor() method Signature: MvcHtmlString DisplayFor(<Expression<Func<TModel,TValue>> expression)

What is the use of display method in HTML?

Display () The Html.Display () is a loosely typed method which generates a string in razor view for the specified property of model. Visit docs.microsoft.com to know all the overloads of Display () method.

What is ToString () method in JavaScript?

JavaScript String toString () Method 1 Definition and Usage. The toString () method returns the value of a String object. 2 Browser Support 3 Syntax 4 Parameters 5 Technical Details

How to print string value to the screen in HTML?

Html.Display and Html.DisplayFor both are used to print string value to the screen. However, you can also use plain HTML tag for displaying text on the screen but Html.Display Extension Method provides more formatting option. Html.Display is loosely typed method whereas Html.DisplayFor is strongly typed method.


1 Answers

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)
like image 143
Russ Clarke Avatar answered Oct 30 '22 01:10

Russ Clarke