从模型验证中排除字段 [英] Exclude Fields From Model Validation

查看:145
本文介绍了从模型验证中排除字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下ViewModel:

    public class PersonViewModel
    {
        [Required]
        public String Email { get; set; }

        [Required]
        public String FirstName { get; set; }

        [Required]
        public String LastName { get; set; }
    }

这是一个ViewModel而不是原始的Entity,我在两个地方都使用了此模型,在第一个地方,我想验证所有字段,但是在另一个地方,我想从模型验证中排除Email字段.无论如何,有没有要指定从验证中排除字段?

This is a ViewModel not a original Entity, I use this model in two places, in the first one I want to validate all fields, but in another one I want to exclude Email field from model validation. Is there anyway to specify to exclude field(s) from validation?

推荐答案

您可以使用

ModelState.Remove("Email");

删除模型状态下与隐藏字段相关的条目.

to remove entries in model state, that are related to hidden fields.

最好的解决方案是将视图模型分为两个:

The best solution is to divide view model into two:

public class PersonViewModel
{
    [Required]
    public String FirstName { get; set; }

    [Required]
    public String LastName { get; set; }
}

public class PersonWithEmailViewModel : PersonViewModel
{
    [Required]
    public String Email { get; set; }
}

这篇关于从模型验证中排除字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆