开发者

Render section with dynamic model in Razor view engine and ASP.NET MVC 3

开发者 https://www.devze.com 2023-03-10 02:57 出处:网络
I have MVC helper method public static string Selected<T>(this HtmlHelper helper, T value1, T value2)

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",
开发者_如何学JAVA            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


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号