是否有可能覆盖在模型的属性所需要的属性? [英] Is it possible to override the required attribute on a property in a model?
问题描述
我很好奇,看看它可以覆盖已设定一个模型[必需]属性。我敢肯定,大多数是一个简单的解决这个问题,任何考生?
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屋!