Reputation: 995
I have a model with a number I'd like to format in a specific way when it is displayed in my view.
[DisplayFormat(DataFormatString = "{### ##}")]
[Display(Name = "Postnr")]
public string CustomerZip;
in the view:
@Html.DisplayFor(modelItem => item.CustomerZip)
In the DB the values are stored as ##### so I get an error when trying this approach: "Input string was not in a correct format". I thought (or rather hoped) that the DataFormatString would reformat the string for me.
Any suggestions on how to do this the best way is appreciated.
Upvotes: 2
Views: 17895
Reputation: 11
Use the Raw function like this:
@Html.Raw(item.Valor.ToString("##,###"))
It works for any type of data.
Upvotes: 1
Reputation: 42497
A few things:
DataFormatString
needs to use the {0:...} indexer style format string, like you'd use in string.Format
. So you'd need to do something like [DisplayFormat(DataFormatString="{0:### ##}"]
. If the braces are supposed to be literal, then you'd use [DisplayFormat(DataFormatString="{{{0:### ##}}}")]
. However...#
for strings. That is what you'd use for a numeric type. If you are storing the value as an integer, then you're in luck; just change the type of CustomerZip
to int.Upvotes: 3
Reputation: 46008
Use following format:
"{0:### ##}"
See example on MSDN page http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.dataformatstring.aspx
Upvotes: 1