是否可以覆盖模型中属性的必需属性? [英] Is it possible to override the required attribute on a property in a model?

查看:30
本文介绍了是否可以覆盖模型中属性的必需属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道是否可以覆盖已在模型上设置的 [Required] 属性.我敢肯定这个问题有一个简单的解决方案,任何人?

I'm curious to find out if it is possible to override the [Required] attribute that has been set on a model. I'm sure there most be a simple solution to this problem, any takers?

推荐答案

取决于您正在做什么.如果您正在使用子类,使用具有必需属性的模型作为基础,您可以这样做:

Depends on what precisely you are doing. If you are working with a subclass, using the model with the Required attribute as the base, you can do this:

使用 new 关键字重新定义属性,而不是覆盖它.

Redefine the property with the new keyword, rather than override it.

public class BaseModel
{
    [Required]
    public string RequiredProperty { get; set; }
}


public class DerivativeModel : BaseModel
{
    new public string RequiredProperty { get; set; }

}

如果您只是想绑定或验证模型,但跳过控制器中的必需属性,您可以执行以下操作:

If you simply want to bind or validate a model, but skip the Required property in your controller, you can do something like:

public ActionResult SomeAction()
{
     var model = new BaseModel();

     if (TryUpdateModel(model, null, null, new[] { "RequiredProperty" })) // fourth parameter is an array of properties (by name) that are excluded
     {
          // updated and validated correctly!
          return View(model);
     }
     // failed validation
     return View(model);
}

这篇关于是否可以覆盖模型中属性的必需属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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