简体   繁体   中英

TryUpdateModel not working with Dictionary<Enum,string>

Assuming these classes\\enums:

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>();
    }
}

This form:

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

And this action:

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

The Model.StringDictionary get's updated successfully.
I can't get the Model.TestDictionary to get updated.

I've tried numerous ways, like changing the inputs name to Test.MyTest1 but couldn't get this to work.

How should my input look like id I want to populate the Model.TestDictionary ?

I found an ugly work-around that works:

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

Anyway, If someone finds something better then it will be nice to see.

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