是否有可能覆盖在模型的属性所需要的属性? [英] Is it possible to override the required attribute on a property in a model?

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

问题描述

我很好奇,看看它可以覆盖已设定一个模型[必需]属性。我敢肯定,大多数是一个简单的解决这个问题,任何考生?

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?

推荐答案

这是什么$ P $取决于pcisely你正在做的。如果您正在使用一个子类的工作,使用与所需的属性为基础的模型,你可以这样做:

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:

重新定义与关键字的财产,而不是将其覆盖。

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天全站免登陆