BrunoLM
BrunoLM

Reputation: 100381

How to use HtmlHelper and AjaxHelper in a razor @helper?

I want to create a helper:

@using System.Web.Mvc
@using System.Web.Mvc.Ajax
@using System.Web.Mvc.Html
@using System.Web.Routing
@using Proj.Extenders
@using Proj.Web.Mvc
@using Proj.Web.Mvc.Paging
@using Proj.Mvc.Helpers
@using Proj.Mvc

@helper Create(dynamic ajaxHelper, dynamic htmlHelper,
    string text,
    string targetID,
    string actionName,
    string controllerName,
    object routeValues,
    string active)
{
    <li@{ if (active == targetID) { <text> class="active"</text> } }>
        @ajaxHelper.ActionLink(htmlHelper.Resource(text).ToString(),
            actionName, controllerName, routeValues, updateTargetId: targetID)
    </li>
}

The problem is that I have extension methods on the HtmlHelper<T> where T is the type of the model. I want to use the same helper for several views, but the @model on the views will be different.

It is not finding the extension method:

'System.Web.Mvc.AjaxHelper<X>' does not contain a definition for 'ActionLink'

ActionLink method

public static MvcHtmlString ActionLink<T>(this AjaxHelper<T> ajax,
    string linkText = " ",
    string actionName = null, string controllerName = null,
    object routeValues = null, object htmlAttributes = null,
    string confirm = null,
    string httpMethod = null,
    InsertionMode insertionMode = InsertionMode.Replace,
    int loadingElementDuration = 0,
    string loadingElementId = null,
    string onBegin = null,
    string onComplete = null,
    string onFailure = null,
    string onSuccess = null,
    string updateTargetId = null,
    string url = null)
{
    var options = GetAjaxOptions(confirm, httpMethod, insertionMode, loadingElementDuration,
        loadingElementId, onBegin, onComplete, onFailure, onSuccess, updateTargetId, url);

    return ajax.ActionLink(linkText, actionName, controllerName, routeValues, options, htmlAttributes);
}

The file is located at

- Website
  - App_Code
     TabHelper.cshtml

How can I use HtmlHelper<T> and AjaxHelper<T> methods on the helper file?

Upvotes: 1

Views: 3327

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

Inline @helper cannot be generic. You will have to use either a standard helper defined as an extension method or or simply some editor/display template or a partial view. This being said in your particular case I don't see why your custom ActionLink must be generic. You end up calling ajax.ActionLink at the end which is not generic.

Upvotes: 1

Related Questions