After a lot of search I found that there is no other way than firing the validations manually as mentioned in this link
Web API Custom ModelBinder Required child object
-
24-06-2023 - |
Pergunta
I am using ASP.NET Web API 2,and I'm trying to validate this child object from my request
the [DataAnnotation Required] is working well on my parent object, but its not working when the a [required] property in child object is missing.
below the sample of my model
In the below posted data, when I'm trying to insert in the table [Users] using the below request (missed the DeviceName in the child object Devices), the [Devices] is not validated against the Data annotations. This means that I don't got an error in the ModelState indicates that the DeviceName field is required. Note: The User object is model binding and validation is working good.
Also the custom ModelBinder is not fired
Model:
[Serializable]
[Table("Users")]
public partial class Users
{
[Key]
[Column("ID")]
public int ID { get; set; }
[Required]
[DataType(DataType.Text)]
[Column("UserName")]
public string UserName { get; set; }
public virtual ICollection<UserDevice> UserDevices { get; set; }
}
[Serializable]
[Table("Users_Devices")]
public partial class UserDevice
{
[Key]
[Column("ID")]
public int ID { get; set; }
[Column("DeviceName")]
[DataType(DataType.Text)]
[Required]
public string DeviceName { get; set; }
[Column("DeviceDescription")]
[DataType(DataType.Text)]
[Required]
public string DeviceName { get; set; }
[Column("UserID", TypeName = "int")]
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual Users User { get; set; }
}
Controller:
public async Task<IHttpActionResult> Post([ModelBinder(typeof(APIUsersModelBinder))] Users user)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
_db.Users.Add(user);
await _db.SaveChangesAsync();
return Created(user);
}
Request Body:
{
"UserName":"TestUser",
"Devices":
[{
"DeviceDescription":"Description"
}]
}
Thanks in advance.
Solução