Home » ASP » ASP.MVC » How to make a Asp.Net MVC HtmlHelper that use generic work with Razor

How to make a Asp.Net MVC HtmlHelper that use generic work with Razor

If you create a Html Helper with Asp.Net MVC that take a generic type, you may stumble into a problem when using it. An error concerning compilation of the page when executing raise with a yellow screen of death.

An exception of type ‘System.Web.HttpCompileException’ occurred in System.Web.dll but was not handled in user code Compiler Error Message: CS1502: The best overloaded method match for ‘System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)’ has some invalid arguments

This code is the result of simply calling this line:

@Html.Test<ContestListItemViewModel>() //Does not work

The Html Helper is very simple.

public static MvcHtmlString Test<TEntityType>(this HtmlHelper htmlHelper)
{
        return new MvcHtmlString("<p>Test</P>");
}

To make it works, you have to have it inside a Razor statement like this:

@{
    var x = Html.Test<ContestListItemViewModel>();
    @Html.Raw(x);
}

The problem is it is not very clean. However, it is possible to fix this with a single line statement if you wrap the Html Helper within parentheses.

@(Html.Test<ContestListItemViewModel>())

How come? Well, Razor become confused if it has to render the result with Html or with C# variable because of the ContestListItemViewModel that is interpreted as Html. Adding parentheses help Razor to generate the Html output and remove the confusion, which remove the error.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

3 Responses so far.

  1. Ricardo says:

    Hi.

    I have this same problem.

    Are you have the solution?

    Please help me.

  2. MAnders says:

    Spot on answer! Thank you very much!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.