user2023653
user2023653

Reputation:

nightmare trying to pass HtmlHelper to a helper

I'm trying to pass an HtmlHelper object to my own helper method, so I can call Html.TextBox within my own helper. I want to do this because the TextBox method accepts an htmlAttributes object that is a very easy way to add attributes dynamically. This is important in my particular case. (I'm trying to create a link that can be clicked on and the text within it edited. There's a javascript callback function involved, and the arguments for this callback will vary depending on what exactly is being saved--hence the need for htmlAttributes object.) The problem is that I cannot seem to pass the Html object to the helper. Here's the code of my helper:

@helper EditLabel(System.Web.WebPages.Html.HtmlHelper html, string id, string text, string defaultText, string linkStyle, object saveFunctionAndArgs)
{    
    string linkText = (string.IsNullOrEmpty(text)) ? defaultText : text;
    <div id="Link_@id">
        <a href="javascript:EditLabel('Link_@id', 'Edit_@id');" style="@linkStyle">@linkText</a>
    </div>    
    <div style="display:none" id="Edit_@id" data-link-id="Link_@id">        
        @html.TextBox("EditLabel", text, saveFunctionAndArgs)        
    </div>
}

This compiles and all is well--btw in my App_Code folder in a .cshtml file. However, when I try to call this from one of my views, the Html object as supplied by my view is not the same type expected in the helper. Here's what the call looks like:

<span>
    @Helpers.EditLabel(Html, id, text, "comment", style, new { saveFunction = "SaveDayuLabel", clinicID = Model["ClinicID"], locationID = Model["LocationID"], date = Model["Date"] })
</span>

What fails is the use of "Html" after @Helpers.EditLabel(. The compiler says there are "invalid arguments." I've done a lot of searching/reading about what this problem might be, but the more I read, the more confused I get. Any suggestions greatly appreciated.

Upvotes: 3

Views: 626

Answers (1)

SLaks
SLaks

Reputation: 887365

Razor helper blocks are compiled to instance methods on the page. (for more detail, see my blog)

You don't need that parameter at all; the helper method can access the same Html property (inherited from the WebViewPage base class) that the rest of the page can.


Your immediate problem is that you declared the helper as taking the ASP.Net WebPages HtmlHelper class (in the System.Web.WebPages.Html namespace), not the MVC version (in System.Web.Mvc).

Upvotes: 2

Related Questions