简体   繁体   中英

ASP.NET Core Binding to a dictionary

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)?

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: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM