Veli Gebrev
Veli Gebrev

Reputation: 2521

MVC4 ModelBinding: Dictionary<int, MyClass[]>

I have an MVC4 web app.

My model contains a Dictionary whose values are an array of one of my own classes.

Given the view below, I'm expecting the default model binder to be able to reconstruct the model/dictionary when I submit to the Post action, however this is not the case.

I do get a MyModel instance and ModelState.IsValid == true, however the dictionary has no key/value pairs in it.

Am I missing something (not adhering to the prescribed convention?) or is this a scenario that requires a custom model binder/digging into the Request.Form collection?

Sample code to reproduce this behaviour:

Model:

public class MyClass
{
    public int MyInt { get; set; }

    public string MyString { get; set; }
}

public class MyModel
{
    public Dictionary<int, MyClass[]> MyDictionary { get; set; }
}

View:

@using (Html.BeginForm("MyAction", "Home", FormMethod.Post))
{
    foreach (var key in Model.MyDictionary.Keys)
    {
        <hr />@key<br />
        for (int i = 0; i < Model.MyDictionary[key].Length; i++)
        {
            @Html.HiddenFor(m => m.MyDictionary[key][i].MyInt);
            @Model.MyDictionary[key][i].MyInt
            @Html.TextBoxFor(m => m.MyDictionary[key][i].MyString);<br/>
        }
    }
    <hr />
    <button type="submit">Post</button>
}

Controller:

[HttpGet]
public ActionResult MyAction()
{
    var model = new MyModel()
    {
        MyDictionary = new Dictionary<int, MyClass[]> {
            {10, new MyClass[] { new MyClass  { MyInt = 1, MyString = "Foo" }, new MyClass { MyInt = 2, MyString = "Bar"}}},
            {20, new MyClass[] { new MyClass  { MyInt = 3, MyString = "Fubar" }}}
        }
    };
    return View(model);
}

[HttpPost]
public ActionResult MyAction(MyModel model)
{
    return View(model);
}

Upvotes: 1

Views: 621

Answers (1)

Jalpesh Vadgama
Jalpesh Vadgama

Reputation: 14226

You need to understand how default model binder from the Hanselman's post.

http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

Here in your case you have taken different controls for key and values and your model binder will not understand what's going on.

Take a look on similar question from the following link. ASP.NET MVC Binding to a dictionary

Upvotes: 2

Related Questions