7

In ASP.NET Core, can you bind dictionary values?

I saw in this related question in a more recent answer (not the one marked correct) it states:

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

Is this also true for ASP.NET Core MVC (and/or Razor Pages)?

Dan
  • 487
  • 5
  • 19
  • 1
    Just a note: Binding to dictionaries works, if you have a `Dictionary`. It will _not_ work (i.e. the value is always null) if you have a `Dictionary`. – Uwe Keim Nov 24 '21 at 07:43

1 Answers1

6

Yes it's also true for ASP.NET Core MVC (and/or Razor Pages).

You can see the following is a simple demo in asp.net core.

Class:

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

Action:

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

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>

Result: enter image description here

Yinqiu
  • 6,609
  • 1
  • 6
  • 14