我有一个包含字典属性的模型。 (这已经从一个较大的项目进入这个例子中,我已经证实还是蒸有同样的问题)MVC3字典不绑定到模型
public class TestModel
{
public IDictionary<string, string> Values { get; set; }
public TestModel()
{
Values = new Dictionary<string, string>();
}
}
控制器
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'
}
}
和视图
@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" />
}
这这样呈现给浏览器:
<input class="text-box single-line" id="Values_foo_" name="Values[foo]" type="text" value="bar" />
我遇到的问题是回发后字典在模型上为空。
- 我是对的吗,还是有更好的办法?
我需要有某种键值存储,因为我的窗体上的字段是可变的,所以我不能使用POCO模型。
好像这个家伙对键值对http://stackoverflow.com/questions/1300642/asp-mvc-net-how-to-bind-keyvaluepair解决 希望这将制定出一个字典 –
@Blast_dan。有趣。字典只是KeyValuePairs的一个集合,所以使用像这样的结构会导致问题是有道理的。我会尝试使用自定义的KeyValuePair类来查看它是否有效。 –
试试EditorTemplate方法,我用List对它进行了测试,检查它是否可以在字典上工作http://www.ienablemuch.com/2012/04/aspnet-mvc-editor-templates.html –