I have a model that contains a dictionary property. (this has been distilled from a larger project into this example, which I have confirmed still has the same issue)
public class TestModel
{
public IDictionary<string, string> Values { get; set; }
public TestModel()
{
Values = new Dictionary<string, string>();
}
}
a controller
public class TestController : Controller
{
public ActionResult Index()
{
TestModel model = new TestModel();
model.Values.Add("foo", "bar");
model.Values.Add("fizz", "buzz");
model.Values.Add("hello", "world");
return View(model);
}
[HttpPost]
public ActionResult Index(TestModel model)
{
// model.Values is null after post back here.
return null; // I set a break point here to inspect 'model'
}
}
and a view
@using TestMVC.Models
@model TestModel
@using (Html.BeginForm())
{
@Html.EditorFor(m => m.Values["foo"]);
<br />
@Html.EditorFor(m => m.Values["fizz"]);
<br />
@Html.EditorFor(m => m.Values["hello"]);
<br />
<input type="submit" value="submit" />
}
This renders to the browser like this:
<input class="text-box single-line" id="Values_foo_" name="Values[foo]" type="text" value="bar" />
The problem I'm having is that the dictionary is null on the model after postback.
- Am I doing this right, or is there a better way?
I need to have some kind of key-value storage, as the fields on my form are variable, so I can't use a POCO model.