【问题标题】:ASP.NET Core Binding to a dictionaryASP.NET Core 绑定到字典
【发布时间】:2020-12-29 06:05:29
【问题描述】:

在 ASP.NET Core 中,可以绑定字典值吗?

我在这个related question 中看到more recent answer(不是标记为正确的那个)它说:

在 ASP.NET MVC 4 中,默认模型绑定器将绑定字典 使用典型的字典索引器语法属性[key]。

对于 ASP.NET Core MVC(和/或 Razor 页面)也是如此吗?

【问题讨论】:

  • 请注意:绑定到字典有效,如果您有Dictionary<string, string>。如果您有Dictionary<string, object>,它将工作(即该值始终为空)。

标签: c# dictionary asp.net-core asp.net-core-mvc model-binding


【解决方案1】:

是的,对于 ASP.NET Core MVC(和/或 Razor 页面)也是如此。

可以看到下面是asp.net core中的一个简单demo。

类:

 public class Command
{
    [Key]
    public string ID { get; set; }
    public string Name { get; set; }
    public Dictionary<string, string> Values { get; set; }
}

行动:

 [HttpPost]
    public IActionResult Test(Command command)
    {
        return View();
    }

查看:

@model Command
<form asp-action="Test">
    <input type="text" name="Id" />
    <input type="text" name="Name" />
    <input type="hidden" name="Values[0].Key" value="Apple" />
    <input type="text" name="Values[0].Value" />
    //....
    <input type="submit" value="Click" />
</form>

结果:

【讨论】:

  • 它是否允许您像这样引用它:
  • 但这不只是将值绑定到字典中的特定“元素”吗?
  • 如果你使用&lt;input type="hidden" name="MyDictionary[MyKey]" value="MyValue" /&gt;,它将绑定到{[Mykey,MyValue]}
  • 是的。会的。
  • 可以看到here
猜你喜欢
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 2017-01-02
相关资源
最近更新 更多