c# - MVC3 字典未绑定(bind)到模型

标签 c# asp.net-mvc-3 dictionary

我有一个包含字典属性的模型。 (这是从一个更大的项目中提炼出来的,我已确认该示例仍然存在相同的问题)

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/

相关文章:

c# - 通过有向图查找路径的递归 lambda 表达式?

c# - WCF DataContracts 中的 INotifyPropertyChanged

.net - 数据注解 MVC3

c# - Invoke() 和 BeginInvoke() 有什么区别

c# - 您可以在代码中配置 log4net 而不是使用配置文件吗?

c# - 检测 WPF ListView 滚动条何时位于底部?

c# - 长时间运行的查询 Web 应用程序( azure )解决方案

javascript - 从两个列表创建一个 json 以在 Javascript 中制作堆积条形图

python - 为什么 dict 文字语法优于 dict 构造函数?

python - 根据值在 Python 字典中选择对象