MVC4模型绑定到字典(破坏变化?)

时间:2012-12-18 14:50:21

标签: c# asp.net-mvc-4 model-binding

我在页面上有以下输入:

@using(Html.BeginForm()) 
{
    @Html.TextBox(String.Format("someData[{0}].Key", 0))
    @Html.TextBox(String.Format("someData[{0}].Key", 1))

    @Html.TextBox(String.Format("someData[{0}].Value", 0))
    @Html.TextBox(String.Format("someData[{0}].Value", 1))

    <input type="submit" value="Go" />
}   

我的印象是发布此数据应通过MVC中的默认模型绑定器绑定到IDictionary。但是,我希望字典的键是数字的:

public ActionResult MyAction(IDictionary<long?, string> someData)
{
    //...
}

我使用Javascript在客户端验证这些字段,但是如果我关闭JS并提交表单而不在框中输入任何内容,我会得到InvalidCastException说模型绑定器无法绑定到someData集合。

我确信在之前版本的MVC中(我们最近已经升级)并且因为Dictionary键可以为(long?),如果为'.Key'输入输入了无效数据(即非数字) ,字典刚刚省略了集合中的条目。

在这种情况下,您可以提交一个没有启用JS的空表单吗?当我提交表单时,我的Action甚至没有被击中(断点)所以我自己无法捕获错误并添加到ModelState ...

1 个答案:

答案 0 :(得分:1)

这适用于我:

[HttpGet]
public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(IDictionary<long?, string> someData)
{
    if (ModelState.IsValid)
    {
        // do some stuff here...
    }
    return View();
}

但是,使用空值发布会产生无效的广告投放,这是已在此处确定的已知问题:http://aspnetwebstack.codeplex.com/workitem/373