【问题标题】:ASP.NET CORE MVC Route: trying to pass a dictionary in asp-all-route-dataASP.NET CORE MVC 路由:尝试在 asp-all-route-data 中传递字典
【发布时间】:2020-07-06 08:44:54
【问题描述】:

所以我有一个我试图传递给另一条路线的对象。

在我的 index.cshtml 中,我正在创建要发送的字典对象:

                    @{
                        var data = new Dictionary<string , ProductToCart>
                        {
                            {"item",  Model }
                         };
                    }

我也有链接标签(在这个视图中)与 asp-all-route-data 以将我的字典传递给如下:

  <a asp-controller="Cart" asp-action="AddToCart" asp-route="productData" asp-all-route-data="data" class="btn btn-lg btn-outline-primary text-uppercase"> <i class="fas fa-shopping-cart"></i> Add to cart </a>

我收到以下错误:

错误 CS0266 无法隐式转换类型 'System.Collections.Generic.Dictionary' 到 'System.Collections.Generic.IDictionary'。明确的 存在转换(您是否缺少演员表?)

问:如何转换这个字典,它是在 ASP.NET CORE MVC 中通过路由传递字典/复杂对象的正确方法?

【问题讨论】:

  • 嗨@Shaz,有关此案的任何更新?您是否使用我们共享的解决方案解决了问题?

标签: c# asp.net dictionary asp.net-core .net-core


【解决方案1】:

无法将类型“System.Collections.Generic.Dictionary”隐式转换为“System.Collections.Generic.IDictionary”。

如果你检查the source code of AnchorTagHelper,你会发现RouteValues被定义为IDictionary&lt;string, string&gt;,如下所示。

/// <summary>
/// Additional parameters for the route.
/// </summary>
[HtmlAttributeName(RouteValuesDictionaryName, DictionaryAttributePrefix = RouteValuesPrefix)]
public IDictionary<string, string> RouteValues
{
    get
    {
        if (_routeValues == null)
        {
            _routeValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        }

        return _routeValues;
    }
    set
    {
        _routeValues = value;
    }
}

如果你想通过路由传递复杂的对象,你可以尝试将其序列化为 json 字符串。

@{

    var data = new Dictionary<string, string>();

    data.Add("item", ((Microsoft.AspNetCore.Html.HtmlString)Json.Serialize(Model)).Value);
}

<a asp-route="productData" asp-all-route-data="data"  class="btn btn-lg btn-outline-primary text-uppercase"> <i class="fas fa-shopping-cart"></i> Add to cart </a>

请注意,如果对象太复杂,可能会超出查询字符串的最大长度限制。

此外,正如@DA 所提到的,实现该要求的另一种方法是实现自定义 AnchorTagHelper。

【讨论】:

    【解决方案2】:

    它不能以默认方式处理复杂类型。 您应该创建自己的自定义标签助手。

    这个article 可以帮助您更多地了解标签助手,here 可以帮助您了解如何创建自己的自定义标签助手。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      相关资源
      最近更新 更多