[英]How can I disable required attribute on a property in a model in web api?
How to disable the [Required]
attribute that has been set on a model property. 如何禁用已在模型属性上设置的[Required]
属性。
I tried with below code using new
keyword but not working. 我尝试使用下面的代码使用new
关键字,但是不起作用。
I also tried override
keyword as well not worked. 我也尝试了override
关键字,以及它不起作用。
ChildModel
uses most of the properties of BaseModel
that's instead of create new model file and code many similar properties I'm thinking to do something like this. ChildModel
使用大部分的属性BaseModel
这不是创造新的模型文件和代码许多相似的性质,我想着做这样的事情的。
public class BaseModel
{
[Required]
public string Address{ get; set; }
}
public class ChildModel : BaseModel
{
public new string Address{ get; set; }
}
Any simple solution ? 任何简单的解决方案?
Simply overriding or redeclaring using the new
keyword on the property and removing the attribute does not work. 简单地使用属性上的new
关键字覆盖或重新声明并删除属性是行不通的。 The way I have always done this is like below.: 我一直这样做的方式如下:
public abstract class BaseModel
{
public abstract string Address { get; set; }
}
public class ChildModel : BaseModel
{
[Required]
public override string Address { get; set; }
}
public class AnotherChildModel : BaseModel
{
//Not[Required]
public override string Address { get; set; }
}
You can read this thread if you want to know more on how attributes of a base class are treated during inheritance. 如果您想了解有关继承期间如何处理基类的属性的更多信息,可以阅读此线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.