Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Why is `ToMvcHtmlString` not public?

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?

like image 261
Deniz Dogan Avatar asked Jul 28 '10 12:07

Deniz Dogan


3 Answers

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.

like image 81
Bradley Mountford Avatar answered Oct 15 '22 03:10

Bradley Mountford


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.

like image 32
Rup Avatar answered Oct 15 '22 02:10

Rup


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);
}
like image 39
BritishDeveloper Avatar answered Oct 15 '22 02:10

BritishDeveloper