我有一个包含字典属性的模型。 (这是从一个更大的项目中提炼出来的,我已确认该示例仍然存在相同的问题)
public class TestModel
{
public IDictionary<string, string> Values { get; set; }
public TestModel()
{
Values = new Dictionary<string, string>();
}
}
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'
}
}
和一个 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" />
}
这会像这样呈现给浏览器:
<input class="text-box single-line" id="Values_foo_" name="Values[foo]" type="text" value="bar" />
我遇到的问题是回发后模型上的字典为空。
- 我这样做对吗,还是有更好的方法?
我需要某种键值存储,因为表单上的字段是可变的,所以我无法使用 POCO 模型。
最佳答案
阅读 Scott Hanselman 关于该主题的博客文章以了解更多详细信息,但同时, 为了解决您的问题,只需将您的 View 替换为以下内容:
<input type="hidden" name="Values[0].Key" value="foo" />
<input type="text" name="Values[0].Value" value="bar" />
对所有部分重复相同的操作,也许将其放入 for 循环中,例如:
@for(i=0;i<Model.Values.Count;i++)
{
@Html.Hidden("Values[@i].Key", @Model.Values.Keys[@i])
@Html.TextBox("Values[@i].Value", @Model.Values.Values[@i])
}
请注意,仅当您使用OrderedDictionary时,您才能通过索引访问键和值。
关于c# - MVC3 字典未绑定(bind)到模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10555917/