简体   繁体   中英

Html helper method not outputting results in mvc view page

My helper looks like:

public static string OutputBlah( this HtmlHelper helper )
{

 return htmlWriter.InnerWriter.ToString();
}

then in my viewpage:

<%= MyHelpers.OutputBlah() %>

Should this be working or am I missing something? Error says that there is no overload that accepts 0 arguements.

What should I be passing into my method in the viewpage?

You are attempting to call an extension method by using a static method call. You can change your code to be

<%= MyHelpers.OutputBlah(Html) %>

But you should probably change it to use it like a proper extension method:

<%= Html.OputputBlah() %>

In order to do this, you need to <%@ Import Namespace="YourHelperNameSpace" %> at the top of the page. Or add it to web.config node.

What does the class declaration look like? Make sure you have made the class itself static as well:

public static class MyHelpers
{
    public static string OutputBlah(this HtmlHelper helper)
    {
        return helper.InnerWriter.ToString();
    }
}

And then use the regular Html property of type HtmlHelper in the View :

<%= Html.OutputBlah() %>

Answer to follow-up question from OP:

When declaring a method like this ( static method in static class , and with the first parameter with the this keyword), you define an Extension Method - a feature that was introduced in C# 3.0. The basic idea is that you define a method that is hooked into another class, thus extending it.

In this case, you're extending the HtmlHelper class (becuase that is the type of the this parameter), and thereby making .OutputBlah() available on any instance of HtmlHelper . If you examine the Html property of the ViewPage , you'll notice that it is in fact of type HtmlHelper .
So when you use Html.OutputBlah() in your view, you're actually accessing the HtmlHelper instance contained in the viewpage's Html property, and calling your own extension method on it.

I think you need to flush the HTML writer. I'm almost sure this is it.

Edit: Plese ignore - I missread the original question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM