With code like the following:
public class FooModel {
public BarModel Bar { get; set; }
}
public class BarModel {
[Required]
public string Baz { get; set; }
}
I want to render FooModel.Bar in a form, but have it be optional. However, the form won’t submit without any input in the text box for BarModel.Baz. Is there a way to go about making the nested model in FooModel optional without having to remove the RequiredAttribute?
Not that I am aware of. I would recommend you using a view model which will be adapted to the requirements of your view (i.e. have the
Bazproperty optional):That’s one of the reasons why you should always use view models and never pass your domain models to the views. As you can see your domain models are not adapted to the specific requirements of the views. You could have some properties required in certain views and optional in other views.