我有一个包含字典属性的模型。 (这是从一个更大的项目中提炼出来的,我已确认该示例仍然存在相同的问题)
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 模型。
请阅读 Scott Hanselman 关于该主题的博客文章以了解更多详细信息,但同时,
为了解决您的问题,只需将您的视图替换为以下内容:
<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])
}
请注意,仅当您使用索引时才可以通过索引访问键和值有序字典 http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)