4

I have an entity that is managed by a WCF service, so the entity is generated through service reference so I cannot annotate it to specify data format. It is decimal and must be formatted with 6 decimals. How can I accomplish this in MVC3, in display and editor?

In display I could use

@Html.Display(format("{0:f4}", model.MyField))

It's not very elegant, but it's workable. But how can I do this for formatting the editor with 4 decimals?

EDIT:

I found this answer to a similar question, but it gives me error in line

return html.TextBox(name, value, htmlAttributes);

Any idea how to solve it?

Thanks

Community
  • 1
  • 1
bzamfir
  • 4,698
  • 10
  • 54
  • 89

2 Answers2

3

Here's an easier syntax:

@Html.Display(model.MyField.ToString("f4"))

If you want to display it in an editable textbox, you could do the same:

@Html.TextBox("myField", model.MyField.ToString("f4"))

Obviously, this doesn't enforce 4 decimals client-side, but it initially displays it with 4 decimals.

[Edit]: In response to your edit: That question's "accepted" answer obviously does not compile, and the comments indicate this too.
Take a look at Gaz's answer because it fixes the compile errors and looks like it works.

Community
  • 1
  • 1
Scott Rippey
  • 15,614
  • 5
  • 70
  • 85
  • Thanks for answer. However, it actually doesn't display anything, neither in view nor in edit - the area is empty. Any idea why? – bzamfir Nov 12 '11 at 02:14
  • Well, I'm not sure if `f4` is correct, I just copied it from your example. I usually use `D4` or `N4`. – Scott Rippey Nov 12 '11 at 05:09
  • Strange, it didn't display anything for me using this approach, but it gave me the idea to make it work. Thanks for suggestion. – bzamfir Nov 15 '11 at 09:45
3

I managed to make it as follows:

  1. For display I used

    @string.Format("{0:f4}", Model.KPINumber)
    
  2. for edit I used

    @Html.TextBox("KPINumber", string.Format("{0:f4}", Model.KPINumber))
    
bzamfir
  • 4,698
  • 10
  • 54
  • 89