asp.net mvc3 中嵌套类型的数据验证

发布于 2024-10-31 01:40:11 字数 1147 浏览 3 评论 0原文

我有以下型号。

public class RoleViewModel
{
    [DisplayName("Role Name")]
    [Required(ErrorMessage="Role Name is required.")]
    [WhiteSpaceAttribute(ErrorMessage="Name cannot contain white space")]
    [StringLength(25, ErrorMessage="Name cannot be be greater than 25 characters")]
    public string RoleName { get; set; }


    [StringLength(100, ErrorMessage = "Description should be less than 100 characters.")]
    public string Description { get; set; }

    [DefaultValue("")]
    public string DisplayMessage { get; set; }


    public bool IsSuccess { get; set; }
}

public class RoleDetailsModel
{
    public RoleViewModel RoleViewModel { get; set; }

    public IList<RoleResourceModel> RoleResources { get; set; }
}

这里,当我在创建角色时使用 RoleViewModel 时,所有验证都会按预期执行。但是,当我使用 RoleDetailsModel (用于编辑)时,不会执行任何验证。

从这里看来,验证针对嵌套类型执行。请告诉我我的理解是否正确。

如果是这种情况,我该如何实现上述情况?简单的方法是在 RoleDetailsModel 中添加相同的验证。但这会违反DRY(不要重复自己)。

更新:实际上我错过了控制器中的 ModelState.IsValid 代码。我已经添加了它,现在它在服务器端工作正常。

感谢您澄清我对嵌套类型部分的理解。

I have following models.

public class RoleViewModel
{
    [DisplayName("Role Name")]
    [Required(ErrorMessage="Role Name is required.")]
    [WhiteSpaceAttribute(ErrorMessage="Name cannot contain white space")]
    [StringLength(25, ErrorMessage="Name cannot be be greater than 25 characters")]
    public string RoleName { get; set; }


    [StringLength(100, ErrorMessage = "Description should be less than 100 characters.")]
    public string Description { get; set; }

    [DefaultValue("")]
    public string DisplayMessage { get; set; }


    public bool IsSuccess { get; set; }
}

and

public class RoleDetailsModel
{
    public RoleViewModel RoleViewModel { get; set; }

    public IList<RoleResourceModel> RoleResources { get; set; }
}

Here, when I am using the RoleViewModel while creating a role, all the validations are executed as expected. However when I use the RoleDetailsModel (for edit), none of the validations are executed.

From here it seems that validations are not executed for nested types. Please let me know if my understanding is correct.

If this is the case, How do I implement the above case? Simple way is to add the same validation in RoleDetailsModel. But this will violate the DRY (Don't Repeat Yourself).

UPDATE: Actually I had missed the ModelState.IsValid code in controller. I have added that and now it is working fine on server side.

Thanks for clearing my understanding on the nested types part.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文