ASP.NET MVC EditorFor css Solution





A Quick solution when trying to format a textbox with CSS, and currency format is a bit tricky in ASP.NET MVC

You can’t put CSS on a Html.EditorFor like you can on a TextBoxFor like so
<%= Html.TextBoxFor(x => x.CostPrice, new { @class = “textShort”, maxlength = “50″ })%>
And you cant put a tag like so (on the model property)
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
public decimal? CostPrice { get; set; }

So basically with TextBoxFor you can use the CSS new { @class = “textShort”, maxlength = “50″ }
but can’t use
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]

And with EditorFor you can use
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
but can’t use
new { @class = “textShort”, maxlength = “50″ }

So you can’t seem to have both without doing some sort of custom templating.

Here is a quick solution for those without much time:
use Html.TextBox like so:
<%= Html.TextBox(“ATLSpend”, Model.ATLSpend.HasValue ? string.Format(“{0:C}”, Model.ATLSpend) : String.Empty, new { @class = “textShort”, maxlength = “50″ })%></li>

happy coding,
Robert Bertora




Tags: , , , ,

Leave a Reply