HTML TextBoxFor in Razor are really useful.
I know that is a bit of an understatement,but they can be even better. I use bootstrap (www.getbootstrap.com) and a number of other js components such as the bootstrap date picker( http://www.eyecon.ro/bootstrap-datepicker/ ) . And by creating my own versions of the helpers we can add a lot of conformity and standardisation. Also if we want to change the control it is in a central place!
Creating our own helper.
The helper needs to be static and return an MvcHtmlString .The new helper is going to be called MyTextBoxFor and will be called in the same way as the original helper, like so.
@Html.MyTextBoxFor( model => model.Name)
For Bootstrap we need to include a class I use "form-control" normally using Razor, we would need to add a class element such as;
@Html.TextBoxFor(model => model.Name, new {@class = "form-control"})
so for our helper we are going to include this.
public static MvcHtmlString MyTextBoxFor(this HtmlHelper helper, Expression > expression, bool addReadonly = false) { var additionalClass = "form-control"; var formatString = string.Empty; return helper.TextBoxFor(expression, formatString, new { @class = additionalClass}); }
Already we are starting to save ourselves some effort, now we can get away with just calling the first snippet rather than the 2nd.
The astute of you will notice the formatString variable in the class, what is that for? As mentioned earlier I use JS components, we can start to plug some of these in.
Expression
the next step is to do a quick query on this and we can start to add some more information
this time we are going to add the datePicker class and a format String ( I like my dates to display like 25-Dec-2015)
public static MvcHtmlString MyTextBoxFor(this HtmlHelper helper, Expression > expression, bool addReadonly = false) { string additionalClass = "form-control"; // add datepicker class to date data types/ Type dataType = expression.Body.Type; var formatString = string.Empty; if (dataType == typeof(DateTime) || dataType == typeof(DateTime?)) { additionalClass = "datePicker form-control"; formatString = "{0:dd-MMM-yyyy}"; } return helper.TextBoxFor(expression, formatString, new { @class = additionalClass}); }
And that is about all there is to it, there is obviously much more you can do, for example Read Only is almost plugged in. You could do spinners for numbers etc.
I hope this helps and enjoy.
Update
I have just added a new blog which uses this technique to display tooltips please see here http://cursethecompiler.blogspot.co.uk/2014/07/tooltip-data-annotation.html