TryUpdateModel不能用于Dictionary

本文关键字:string Enum 不能 用于 Dictionary TryUpdateModel | 更新日期: 2023-09-27 17:49:39

假设这些类:

public enum Test
{
    MyTest1 = 0,
    MyTest2,
    MyTest3,
}
public class Model
{
    public Dictionary<Test, string> TestDictionary { get; set; }
    public Dictionary<string, string> StringDictionary { get; set; }
    public string Other { get; set; }
    public Model()
    {
        TestDictionary = new Dictionary<Test, string>();
        StringDictionary = new Dictionary<string, string>();
    }
}

这种形式:

<form action="/Home/Test" method="post">
    <input type="hidden" name="Model.TestDictionary[MyTest1]" value="myval" />
    <input type="hidden" name="Model.StringDictionary[mykey]" value="myval" />
    <input type="hidden" name="Model.StringDictionary[mykey2]" value="myval2" />
    <input type="hidden" name="Model.Other" value="works" />
    <button type="submit">Submit</button>
</form>

这个动作:

public ActionResult Test(FormCollection formCollection)
{
    Model model = new Model();
    TryUpdateModel(model, "Model");
    return Redirect("Index");
}

Model.StringDictionary get更新成功。
不能Model.TestDictionary得到更新

我已经尝试了许多方法,如将输入名称更改为Test.MyTest1,但无法使此工作。

如果我想填充Model.TestDictionary,我的输入应该是什么样子?

TryUpdateModel不能用于Dictionary<Enum,string>

我发现了一个丑陋的解决方案:

<input type="hidden" name="Model.TestDictionary[0].Key" value="MyTest1" />
<input type="hidden" name="Model.TestDictionary[0].Value" value="myval" />

无论如何,如果有人找到更好的东西,那就太好了。