1

I have MVC helper method

public static string Selected<T>(this HtmlHelper helper, T value1, T value2)
    {
        if (value1.Equals(value2))
            return "class=selected";
        return String.Empty;
    }

But when I call it from view

 @Html.Selected(item.DomainID, Model.DomainID)>

or cast it as explained here

@Html.Selected(item.DomainID, (int)(Model.DomainID))>

My view looks like this

@model FYP.Models.ProjectIdea
@using Helpers
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
<p class="validation-summary-errors">@ViewBag.Message</p>
@section LeftColumn{
<ul id="leftColumn">
@foreach (var item in ViewBag.Model.Domains)
{
    <li @Html.Selected(item.DomainID, Model.DomainID)>
        @Html.ActionLink(item.Title, "Index",
            new { id = item.DomainID },
            new
            {
                @id = "navLink:" + item.DomainID
            }
        )
</li>
}
</ul>
 }

I get the following error.

Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'Selected' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

Any help?

Update:

Ok I got it working by changing the argument types to int

public static string Selected<T>(this HtmlHelper<T> helper, int value1, int value2)
{
    if (value1.Equals(value2))
        return "class=selected";
    return String.Empty;
}

Though this is not generic any more bust still solved my problem

Community
  • 1
  • 1
Saqib
  • 1,283
  • 1
  • 13
  • 16

1 Answers1

1

Try changing the HtmlHelper type to a generic one (note the generic T)...

public static string Selected<T>(this HtmlHelper<T> helper, T value1, T value2)
{
    if (value1.Equals(value2))
        return "class=selected";
    return String.Empty;
}
Kieron
  • 26,748
  • 16
  • 78
  • 122
  • :( still getting the same error after changing `HtmlHelper` type to `T` – Saqib Jun 01 '11 at 09:59
  • Can you try casting your dynamic (assuming DoaminID on one of your variables is) types to it's actual type? – Kieron Jun 01 '11 at 10:14
  • OK it works now. The trick is to remove generic type from HtmlHelper and casting the arguments to actual types. `public static string Selected(this HtmlHelper helper, T value1, T value2) { if (value1.Equals(value2)) return "class=selected"; return String.Empty; }` – Saqib Jun 01 '11 at 10:25