I'm trying to write my own little HTML helper which acts a lot like DropDownListFor
but which doesn't suffer from the same problems that I've encountered before. Let's not discuss whether or not DropDownListFor
is flawed—that is not what this question is about.
Anyways, what is the reason that the MVC guys make ToMvcHtmlString
internal and not public?
I thought I'd post an easy workaround for those that might be looking for one and stumble upon this question.
While ToMvcHtmlString is internal, it is pretty easy to bypass as it uses public methods:
From the MVC source:
internal MvcHtmlString ToMvcHtmlString(TagRenderMode renderMode) {
return MvcHtmlString.Create(ToString(renderMode));
}
Both MvcHtmlString.Create and TagBuilder.ToString are public so just replace
return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);
with
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
and you are good to go! Works great for me. Not sure why they even bothered to make a separate internal method.
My guess is to encourage you to use System.Web.HtmlString instead. But yes, I've wondered this myself and I've written a duplicate ToMvcHtmlString extension in my own helpers.
MvcHtmlString is, IIRC, just their compatibility fix so MVC 2 can work on both .NET 3.5 and 4 - but even then it'd be useful to use in your own code for that.
Does this solve your problem?
public static MvcHtmlString SuperDenizControl(this HtmlHelper html)
{
var builder = new TagBuilder("select");
//blah blah blah amazing control
var control = builder.ToString();
return MvcHtmlString.Create(control);
}
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