2012-07-19 675 views
0

我有两个视图模型,一个聚集了其他的集合:使用RemoteAttribute嵌套子集

class Parent 
{ 
    public string Key { get; set; } 
    public IList<Child> Children { get; set; } 
} 

class Child 
{ 
    public string Key { get; set; } 

    [Required, Remote("VerifyNameUnique", "Parent", AdditionalFields = "Key", ErrorMessage = "The name must be unique.")] 
    public string Name { get; set; } 
} 

我有一个控制器动作

public ActionResult VerifyNameUnique(string key, string name) 
{ 
    var result = // ... verify uniqueness 
    return Json(result, JsonRequestBehavior.AllowGet); 
} 

和一个视图:

@model Parent 
@Html.HiddenFor(m => m.Key) 
@for(var i=0; i<Model.Children; i++) 
{ 
    @Html.HiddenFor (m => m.Children[i].Key) 
    @Html.LabelFor(m => m.Children[i].Name) 
    @Html.EditorFor (m => m.Children[i].Name) 
} 

当我的父/子编辑器模板调用验证任何Name字段的动作时,它会发送查询字符串?Children[0].Key=abc&Children[0].Name=Fred,其中0是刚刚编辑的孩子的索引i

由于前缀不匹配VerifyNameUnique的参数。我已尝试使用BindAttribute设置前缀,但前缀因值i而异。

编写一个自定义模型联编程序是一个选项,但对于这个简单的场景来说现在看起来有点过分了。有什么更好的,我可以做吗?

回答

1

这根本不被支持。因此,您将不得不编写自定义模型绑定器或自定义“远程验证”属性。这就是说,你试图达到的目的可能不是一个好主意,因为如果用户点击提交按钮,AJAX请求将被发送到集合中的每个字段都不是很有效。我可能会直接在父级的集合属性上使用自定义远程验证字段,以便通过单次往返服务器验证所有内容。

+0

谢谢。据我所知,AJAX请求仅在用户更改字段而不是未更改字段时才会生成,因此在性能方面看起来不错。 – 2012-07-19 14:45:52

+0

请直接点击提交按钮。不用改变任何东西 – 2012-07-19 14:46:23

+0

不,你是对的 - 它确实会解雇他们。 – 2012-07-19 14:48:46