【问题标题】:Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access无效的匿名类型成员声明符。必须使用成员分配、简单名称或成员访问来声明匿名类型成员
【发布时间】:2012-02-08 15:55:21
【问题描述】:

我正在尝试将附加属性 data-icon 添加到我的操作链接,但出现以下错误:

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

作品:

@Html.ActionLink("Profile", "Details", "Profile", new { id = 11 }, 
            new { @rel = "external", @id = "btnProfile" })

例外:

@Html.ActionLink("Profile", "Details", "Profile", new { id = 11 }, 
            new { @rel = "external", @id = "btnProfile", @data-icon = "gear" })

【问题讨论】:

标签: asp.net-mvc-3 c#-4.0 razor


【解决方案1】:

更新:从上面 Xander 的评论中,使用 data_icon = "gear"

您可以使用IDictionary<string, object> 代替 HTML 属性的匿名对象:

@Html.ActionLink("Profile", "Details", "Profile", new { id = 11 }
    , new Dictionary<string, object>
    {
        { "rel", "external" }, 
        { "id", "btnProfile" },
        { "data-icon", "gear" },
    })

查看此重载:http://msdn.microsoft.com/en-us/library/dd504988.aspx

您使用的助手只是创建字典的一种便捷方法,但无论如何在幕后创建字典。

【讨论】:

  • 当我这样做时,它会呈现如下链接:&lt;a comparer="System.Collections.Generic.GenericEqualityComparer1[System.String]" count="1" keys="System.Collections.Generic.Dictionary2+KeyCollection[System.String,System.Object]" values="System.Collections.Generic.Dictionary2+ValueCollection[System.String,System.Object]" href="/Account/LogOff/1" class="ui-link"&gt;Log Off&lt;/a&gt;
  • 我的参数中的句点/点有这个问题(一个我想传递的成员的类过滤器),我发现以下工作......@Html.ActionLink("Profile", "Details", new RouteValueDictionary{ {"filter.member", myvalue.ToString() } } )希望格式化工作 -基本上使用 RouteValueDictionary 而不是匿名类型?
【解决方案2】:

我认为您使用像 data_icon 这样的下划线,它会翻译它

【讨论】:

  • 完美答案。
【解决方案3】:

我只是用下面的

@using System.Web.Routing

@{
    RouteValueDictionary RouteValues = new RouteValueDictionary();

    RouteValues["id"] = 11;
    RouteValues[Some_Name] = Some_Value; //do this with as many name/value pairs 
                                         //as you like
}

@Html.ActionLink("Link Text", "Action", "Controller", RouteValues)

我从 Jon 在 this post 的回答中了解到。

我主要在我的控制器中使用它来为RedirectToAction() 方法提供路由值,但我不明白为什么它在您的视图中不起作用,但您需要添加@using System.Web.Routing;

【讨论】:

    【解决方案4】:

    使用“data_icon”而不是“data-icon”。

            @Html.ActionLink("Profile", "Details", "Profile", new { id = 11 }, 
            new { @rel = "external", @id = "btnProfile", @data_icon = "gear" })
    

    在生成的标记中,_ 将自动转换为 -。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      • 2015-01-11
      相关资源
      最近更新 更多