This is why I'm so unhappy with the MVC team's decision to use strings everywhere. Adding a class to a textbox should not be the concern of the TextBox HtmlHelper, it should be a separate aspect of building HTML. Here is a better solution using a semantic model to define Html. I'm going to use TagBuilder here, but I highly recommend looking into the HtmlTags library included with FubuMvc.
public TagBuilder TextBox(this HtmlHelper helper, string name, string value)
{
var tag = new TagBuilder("input");
tag.MergeAttribute("type", "text");
tag.MergeAttribute("name", name);
tag.MergeAttribute("value", value);
return tag;
}
Now since we're returning a semantic (TagBuilder) model, we can continue to modify the model before converting it to an HTML literal. ConditionallyAddClass is a reusable extension method that will apply a class to any TagBuilder model:
public TagBuilder ConditionallyAddClass<T>(this TagBuilder tag, string @class, T model, Func<T, bool> condition)
{
if(condition(model))
{
tag.AddCssClass(@class);
}
return tag;
}
In your view you can now do this (assuming StyleAgeTextbox is a boolean property):
<%= Html.TextBox("Age", Model.Age).ConditionallyAddClass("customClass", Model, m => m.StyleAgeTextbox) %>
The view engine would automatically call ToString() on the TagBuilder to get the proper HTML.
I hope this gives you the basic idea. There are of course many ways you can extend this. You could have a standard naming convention and use a dynamic
type to get around using expressions or you could have lookup tables or strongly type the entire thing to use member expressions (eg TextBoxFor(m => m.Age)). I prefer moving the entire thing into an html convention framework like Fubu does, but that's probably beyond most projects.