我在一个页面上有以下输入:
@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版本中(我们最近升级了),并且因为字典键可以为空(long?),所以如果为'.Key‘输入输入了无效数据(即非数字),字典就会忽略集合中的条目。
在这种情况下,您肯定可以在没有启用JS的情况下提交一个空表单?当我提交表单时,我的操作甚至没有命中(断点),所以我自己无法捕获错误并添加到ModelState中……
发布于 2012-12-18 23:56:14
这对我来说很好用:
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IDictionary<long?, string> someData)
{
if (ModelState.IsValid)
{
// do some stuff here...
}
return View();
}但是,使用空值进行cast将产生无效的强制转换,这是一个已知问题,已在此处确定:http://aspnetwebstack.codeplex.com/workitem/373
https://stackoverflow.com/questions/13935492
复制相似问题