views:

89

answers:

1

I'm using MVC 2. I want to format the data that I display in my textbox when I edit a record.

I display my textbox like this:

<%: Html.TextBoxFor(m => m.AnnualIncome, new { @class = "textbox", maxlength = "50", size = "15" })%>

How would I format this? I tried adding the String.Format from below but it does not work:

<%: Html.TextBoxFor(model => model.AnnualIncome, String.Format("{0:F}", Model.AnnualIncome)) %>

AnnualIncome is of type Nullable decimal.

EDIT:

I am putting in a thousands separator to give me a value like 1,000,000 just to see the result.

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:0,0}")]
public Nullable<decimal> AnnualIncome { get; set; }

Here is my HTML for the above:

<%: Html.TextBoxFor(m => m.AnnualIncome, new { @class = "textbox", maxlength = "50", size = "15" })%>

This still displays 1000000.00. I am trying to get it to display 1000000 in the textbox when the view is populated.

+3  A: 

Put a DisplayFormatAttribute.DataFormatString attribute on the property:

[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:F}")]
public float AnnualIncome { get; set; };

Then you just do:

<%: Html.EditorFor(m => m.AnnualIncome) %>

To style the inputs, you can do:

input.editor-field {
    color: #781351;
}

...or whatever you prefer.

Craig Stuntz
Not working, check above my new edits.
Brendan Vogt
Html.EditorFor works fine, but it doesn't use the styling that I provide. Why does EditorFor work and not TextBoxFor?
Brendan Vogt
`EditorFor` uses the model metadata. `TextBoxFor` doesn't. I should have suggested `EditorFor`. What styling are you trying to preserve.
Craig Stuntz
The textbox that the EditorFor displays looks like a plain HTML input control. It uses some sort of default styling. I don't use that styling, I have my own style that I apply to my textboxes. How do I apply my style to the input textbox that the EditorFor creates?
Brendan Vogt
You add a CSS rule. I'll add to the answer.
Craig Stuntz