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.
A few things:
DataFormatStringneeds to use the {0:…} indexer style format string, like you’d use instring.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 ofCustomerZipto int.