0

我正在构建一个 htmlhelper 扩展,但收到此错误:

无效的匿名类型成员声明符。必须使用成员分配、简单名称或成员访问来声明匿名类型成员。

我试图将@User.IsInRole 转换为布尔值但无济于事:(

这是 Razor 标记:

@using htmlHelperstring.Models
@{
    ViewBag.Title = "Home Page";

}

<ul>
    @Html.MyActionLink(
    "<span>Hello World</span>", 
    "about", 
    "home",
    new { id = "123" },
    new { @class = "foo",(bool)(@User.IsInRole("Chef"))}
)
</ul>

帮手:

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace htmlHelperstring.Models
{
    public static class LabelExtensions
    {
        public static IHtmlString MyActionLink(
        this HtmlHelper htmlHelper,
        string linkText,
        string action,
        string controller,
        object routeValues,
        object htmlAttributes,
            bool UserAuthorized
    )
        {
            var li = new TagBuilder("li");
            if (UserAuthorized)
            {
                var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
                var anchor = new TagBuilder("a");
                anchor.InnerHtml = linkText;
                anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
                anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
                li.InnerHtml = anchor.ToString();
            }
            else
            {
                li.InnerHtml = string.Empty;
            }
            return MvcHtmlString.Create(li.ToString());
        }
    }
}
4

3 回答 3

1

看起来您缺少以下成员分配:

new { @class = "foo",(bool)(@User.IsInRole("Chef"))} 

您要将布尔值分配给什么?

你需要这样的东西:

new { @class = "foo", HTMLATTRIBUTENAME = (bool)(@User.IsInRole("Chef"))} 

将 HTMLATTRIBUTENAME 替换为您要设置的属性名称。

于 2012-08-29T07:16:45.163 回答
0

我不写 asp.net (实际上从来没有写过一行;所以请谨慎对待);但我怀疑构造:

new { id = "123" }

(以及它下面的类似内容)是“匿名类型”所指的消息,我对为什么你所拥有的可能是错误的有一些想法(最有可能是第三种感觉)。

首先,如果它是 C 风格的结构,您可能需要使用 '.' 在“成员”标识符之前(对我来说,这对于该错误消息是有意义的):

new { .id = "123}

其次,该错误的措辞让我想知道在这种环境中是否不允许您传递这样的匿名对象;您需要先将其分配给一个变量,然后再传递该变量。原谅任何语法错误:

@using htmlHelperstring.Models
@{
    ViewBag.Title = "Home Page";
    myID = new { id = 123 };
    myClass = new { @class = "foo",(bool)(@User.IsInRole("Chef"))}
}

<ul>
    @Html.MyActionLink(
    "<span>Hello World</span>", 
    "about", 
    "home",
    myID,
    myClass
)
</ul>

第三new { @class = "foo",(bool)(@User.IsInRole("Chef"))},对我来说看起来很奇怪的语法。也许(注意添加成员名称):new { @class = "foo", isChef = (bool)(@User.IsInRole("Chef"))}

于 2012-08-29T07:19:12.073 回答
0

我只是犯了一个愚蠢的错字(一天结束等)它应该是:

@{ 
    ViewBag.Title = "Home Page"; 
    myID = new { id = 123 }; 
    myClass = new { @class = "foo"},(bool)(@User.IsInRole("Chef")) 
} 
于 2012-08-30T00:27:43.903 回答