I have a controller which take a model as parameter. This model is a specialized version of a generic model. I want my specialized model to hide a required base field to make it not required.
Here is what I did :
Controller
public class TestController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(new SpecializedModel());
}
[HttpPost]
public ActionResult Index(SpecializedModel model)
{
if(ModelState.IsValid)
{
//Do some stuff, eventually redirect elsewhere
}
return View(model);
}
}
GenericModel
public class GenericModel
{
[Required(ErrorMessage = "The field is required.")]
public string SomeValue { get; set; }
}
SpecializedModel
public class SpecializedModel : GenericModel
{
new public string SomeValue { get; set; }
}
View
<form method="post">
@Html.TextBoxFor(model => model.SomeValue)<br />
@Html.ValidationMessageFor(model => model.SomeValue)<br />
<input type="submit" />
</form>
When I validate the form, the error message
The field is required.
is shown. I gather the RequiredAttribute
is kept... is there a way to get rid of it ?
Edit : I also tried to make the SomeValue
a virtual field to override it, but the problem is the same.