0

我想用模型中的数据填充一个动作链接列表。为了实现这一点,我创建了一个名为 ActionLinkModel 的模型

public class ActionLinkModel
{
    public ActionLinkModel(string linkText, string actionName = "Index", string controllerName = "Home", Dictionary<string, string> routeValues = null, Dictionary<string, string> htmlAttributes = null)
    {
        LinkText = linkText;
        ActionName = actionName;
        ControllerName = controllerName;
        RouteValues = routeValues == null ? new Dictionary<string, string>() : routeValues;
        HtmlAttributes = htmlAttributes == null ? new Dictionary<string, string>(): htmlAttributes;
        if(!HtmlAttributes.ContainsKey("title")) {
            HtmlAttributes.Add("title",linkText);
        }
    }

    public string LinkText { get; set; }
    public string ActionName { get; set; }
    public string ControllerName { get; set; }
    public Dictionary<string, string> RouteValues { get; set; }
    public Dictionary<string, string> HtmlAttributes { get; set; }

}

然后在我看来,我这样称呼它:

@foreach (var link in Model.Links) {
   @Html.ActionLink(link.LinkText, link.ActionName, link.ControllerName, link.RouteValues, link.HtmlAttributes);
} 

不幸的是,这并没有按照我希望的方式呈现,问题在于路由值和 htmlAttibutes。我无法弄清楚它们需要什么类型,在 Html.Actionlink 的签名中,我看到它们要么是对象,要么是 RouteValueDictionary / IDictionary。我也见过这样的结构:

Html.ActionLink("Home", "Index", "Home", null, new { title="Home", class="myClass"})

但是创建的是什么类型 new { title="Home", class="myClass"}

我该怎么做?,我想处理模型中的事情,并使视图中的代码尽可能简单。

4

1 回答 1

1
new { title="Home", class="myClass"} 

使用提供的属性值转换为匿名对象。

要回答您的问题,您需要将 Model 对象修改为以下内容。字典对象需要是Dictionary<string,object>.

public class ActionLinkModel
{
    public string LinkText { get; set; }
    public string ActionName { get; set; }
    public string ControllerName { get; set; }
    public IDictionary<string, object> RouteValues { get; set; }
    public IDictionary<string, object> HtmlAttributes { get; set; }
}

并在视图代码中使用以下

@foreach (var link in Model.Links) {
    @Html.ActionLink(link.LinkText, link.ActionName, link.ControllerName, new RouteValueDictionary(model.RouteValues), model.HtmlAttributes)
} 

我们将字典对象包装到一个RouteValueDictionary. 如果您不这样做,那么它将Object被 CLR 转换为重载,并给出不正确的结果。

于 2013-10-22T13:32:02.130 回答