Is it possible to inject a css class into an HTML element that has been encapsulated within an MvcHtmlString
?
I've been tasked, as part of the framework I'm building, with creating my own versions of the MVC extension methods for form elements (TextBox
, TextBoxFor<>
, etc), with the following caveats:
Most, if not all, of the MVC extension methods return an MvcHtmlString
so the simplest way to mimic the functionality is to call those methods directly from my methods. I have my own Html Helper, OuHelper
, that my framework is using, so developers wishing to create, for example, a TextBox
, would call something along the lines of:
`@Ou.TextBoxFor(m => m.Username)
And I would like the resulting Html to render like so:
<input type="text" name="Username" id="Username" class="int-text" />
If I create my own versions of the overloads as they are in the MVC framework, I will be able to control adding the extra CSS classes where needed but that seems like overkill for such a small change of HTML output from those methods. I would need to provide equivalent implementations of all of the overloads (for TextBox
alone there are about 12 when you count the generic and non-generic versions). What I would like to do is TagBuilder
in reverse (start with the output and create an object from it that will enable things like MergeAttributes
to be available) but I don't think that's possible.
To be clear: the framework code that I am writing needs to add the css classes itself, but it should be possible for developers using the extension methods that I create to add their own custom css classes as well. These would be added/appended as per the standard MVC framework form extension methods' functionality
You seem to have a pretty good system currently. You can't inject/override the default styles for the HtmlHelper classes , you can check out the source for HtmlHelper
's input extensions here if you want.
The only other way I can think of doing it would be using extension methods much like how its done in the actual ASP.NET source. Here is an example, the name of the function could be anything you want but it needs to be different from TextBoxFor
as it has the same parameter list.
public static class HtmlHelperExtensions
{
public static MvcHtmlString IntTextFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return htmlHelper.TextBoxFor(expression, new { @class = "int-text" });
}
}
Usage would be just like regular MVC only include the namespace of your extension method(s).
@using MyProject.Helpers;
@Html.IntTextFor(e => e.Age)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With