【问题标题】:Generate actionlinks with model data使用模型数据生成操作链接
【发布时间】:2013-10-22 13:02:53
【问题描述】:

我想用来自模型的数据填充动作链接列表。为了实现这一点,我创建了一个名为 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, 新 { title="Home", class="myClass"})

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

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

【问题讨论】:

    标签: c# asp.net asp.net-mvc-4


    【解决方案1】:
    new { title="Home", class="myClass"} 
    

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

    要回答您的问题,您需要将 Model 对象修改为以下内容。字典对象需要是Dictionary&lt;string,object&gt;

    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。如果你不这样做,那么它将被 CLR 转换为 Object 重载,并给出不正确的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-23
      • 1970-01-01
      • 2011-08-20
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      相关资源
      最近更新 更多