如何进行模型验证以拾取 MVC3 中列表中对象的属性集?

发布于 2025-01-01 00:27:17 字数 494 浏览 2 评论 0原文

我有一组与此类似的模型

public class OtherModel 
{
    [Required]
    string name { get; set; }
}

public class OthersEditModel 
{
    List<OtherModel> others { get; set; }
}

,然后有一个与此类似的控制器方法。

[HttpPost]
public ActionResult EditOthers(OthersEditModel others)
{
    if(ModelState.IsValid)
    {
         // Save
    }
}

我的问题是 ModelState.IsValid 没有触发列表中对象的验证。

我该如何实现这一点,或者甚至可能吗?

或者我可以手动触发列表中元素的验证吗?

I have a set of models that looks similar to this

public class OtherModel 
{
    [Required]
    string name { get; set; }
}

public class OthersEditModel 
{
    List<OtherModel> others { get; set; }
}

I then have a controller method that looks like this

[HttpPost]
public ActionResult EditOthers(OthersEditModel others)
{
    if(ModelState.IsValid)
    {
         // Save
    }
}

My problem is that the ModelState.IsValid isn't triggering the validation of the objects in the list.

How do I accomplish this, or is it even possible?

Or alternatively can I manually trigger the validation of the elements in the list?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

任谁 2025-01-08 00:27:17

所以事实证明问题不在于验证属性。它们完美地拾取,无需对基础 OthersEditModel 进行任何操作。我破坏了动态 JavaScript 表单生成,因此表单字段返回时名称不正确。

顺便说一句,这个 http://haacked. com/archive/2008/10/23/model-binding-to-a-list.aspx 是 MVC 3 的出色扩展

So it turns out that the problem wasn't the validation properties. They pick up perfectly, without doing anything to the base OthersEditModel. I had broken the dynamic JavaScript form generation, so the form fields were coming back with incorrect names.

By the way, this http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx is an excellent extension to MVC 3

江南烟雨〆相思醉 2025-01-08 00:27:17
[HttpPost]
public ActionResult EditOthers(OthersEditModel others)
{
    if(ModelState.IsValid)
    {
         foreach (var item in others.others)
        {
            if(!TryValidateModel(item))
                //Not valid
        }
    }
}
[HttpPost]
public ActionResult EditOthers(OthersEditModel others)
{
    if(ModelState.IsValid)
    {
         foreach (var item in others.others)
        {
            if(!TryValidateModel(item))
                //Not valid
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文