I would like to “turn off” the Required field validation on a certain property of the parent model (VehicleManufacturer), when saving a child model (VehicleModel), i.e.:
public class VehicleManufacturer
{
public virtual Guid Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
public virtual string Name { get; set; }
}
public class VehicleModel
{
public virtual Guid Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
public virtual string Name { get; set; }
public virtual VehicleManufacturer Manufacturer { get; set; }
}
So, when I’m saving a new model, all I care about is it’s Name and ManufacturerID, which would be selected from a drop-down list, however, because the ManufacturerName is marked [Required] in its entity, it invalidates my ModelState when saving a new VehicleModel, because ManufacturerName is null 🙁
I would like to know what is the best approach to this and how to do it.
I can think of a few solutions but none seem to be the right way:
- Set a “default” ManufacturerName value before ModelState check, i.e.
“-” just to satisfy the DataAnnotation - Populate both ManufacturerName
and ManufacturerId in my VehicleModelView – not good if your parent
model has a bunch of required field you don’t really need to use in a
child model - Turn off [Required] validation for child model (not sure
how?)
what do you think?
A possible solution is to add the foreign key column to the VehicleManufacturer (VehicleManufacturerId) to the VehicleModel and use that column in your view.