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 theMvcHtmlStrings 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.