ekenman
ekenman

Reputation: 995

Format numbers in MVC view

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

Answers (3)

Eduardo Sierra
Eduardo Sierra

Reputation: 11

Use the Raw function like this:

@Html.Raw(item.Valor.ToString("##,###"))

It works for any type of data.

Upvotes: 1

moribvndvs
moribvndvs

Reputation: 42497

A few things:

  1. The 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...
  2. There is no such format character # 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.
  3. If you are NOT storing the value as an integer, but as a string (as you are wont to do with postal codes, usually), then you've got more of a problem. Like I said, you don't have any custom format options with strings. You'd need to represent CustomerZip as some custom type that is IFormattable, which you would define.

Upvotes: 3

Related Questions