c# - How to inject a css class into an MvcHtmlString? -
is possible inject css class html element has been encapsulated within mvchtmlstring
?
i've been tasked, part of framework i'm building, creating own versions of mvc extension methods form elements (textbox
, textboxfor<>
, etc), following caveats:
- that must create correct html markup, including css classes, match styles have been designed site. in majority of cases, means addition of specific class.
- that must true mvc extension methods possible developers feel comfortable using them
most, if not all, of mvc extension methods return mvchtmlstring
simplest way mimic functionality call methods directly methods. have own html helper, ouhelper
, framework using, developers wishing create, example, textbox
, call along lines of:
`@ou.textboxfor(m => m.username)
and resulting html render so:
<input type="text" name="username" id="username" class="int-text" />
if create own versions of overloads in mvc framework, able control adding css classes needed seems overkill such small change of html output methods. need provide equivalent implementations of of overloads (for textbox
alone there 12 when count generic , non-generic versions). tagbuilder
in reverse (start output , create object enable things mergeattributes
available) don't think that's possible.
to clear: framework code writing needs add css classes itself, should possible developers using extension methods create add own custom css classes well. these added/appended per standard mvc framework form extension methods' functionality
you seem have pretty system currently. can't inject/override default styles htmlhelper classes , can check out source htmlhelper
's input extensions here if want.
the other way can think of doing using extension methods how done in actual asp.net source. here example, name of function want needs different textboxfor
has 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 regular mvc include namespace of extension method(s).
@using myproject.helpers; @html.inttextfor(e => e.age)
Comments
Post a Comment