ASP.NET 核心绑定到字典

ASP.NET Core Binding to a dictionary

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

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

In ASP.NET MVC 4, the default model binder will bind dictionaries using the typical dictionary indexer syntax property[key].

ASP.NET Core MVC(and/or Razor Pages)也是如此吗?

是的,ASP.NET Core MVC(and/or Razor Pages)也是如此。

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

Class:

 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>

结果: