Is there any possible way to extend the basic html helpers (TextBoxFor
, TextAreaFor
, etc) using extension methods on their output, instead of just re-writing the entire methods completely? For instance, adding in ...
@Html.TextBoxFor( model => model.Name ).Identity("idName")
I know I can achieve this using the following, already..
@Html.TextBoxFor( model => model.Name, new { @id = "idName" })
But that gets clunky and frustrating to manage when you have to start adding a lot of properties. Is there any way to add extensions to these inherently without just passing in htmlAttributes
for every little detail?
As @AaronShockley says, because
TextBoxFor()
returns anMvcHtmlString
, your only option for developing a 'fluid API' style of amending the output would be to operate on theMvcHtmlString
s returned by the helper methods. A slightly different way of doing this which I think approaches what you're after would be to use a 'property builder' object, like this:...and to set up extension methods like this:
You can then do stuff like this in your View:
This gives you strong typing and intellisense for input properties, which you could customise for each extension method by adding properties to an appropriate MvcInputBuilder subclass.
All of the basic html helpers return an object of type
System.Web.Mvc.MvcHtmlString
. You can set up extension methods for that class. Here is an example:Then you can use these in a view like:
To make extension methods that modify attributes on the rendered HTML tag, you'll have to convert the result to a string, and find and replace the value you're looking for.
The
id
andname
attributes are always added by the html helpers, but if you want to work with attributes that may not be there (and you'll have to add them instead of just replacing them), you'll need to modify the code.