In class I have this :
public class CustomerMvc
{
public int Id { get; set; }
[Required(ErrorMessage = "LastName mandatory.")]
public string LastName { get; set; }
[EmailValidation(ErrorMessage = "Email not valid.")]
public string Email { get; set; }
}
In another class, I have this :
public class CartMvc
{
public CustomerMvc Customer { get; set; }
[Required(ErrorMessage = "VAT mandatory.")]
public int VatId { get; set; }
}
A Save
method int the controller, receive a model type CartMvc
. The problem is, in this case, I don't want validate the property type CustomerMvc
but only VatId
.
Is there a way to bypass, in this case, the validation on CustomerMvc
? Other way ?
Thanks,
You could use a view model:
public class SaveCustomerMvcViewModel
{
public int Id { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
and then:
public class SaveCartMvcViewModel
{
public SaveCustomerMvcViewModel Customer { get; set; }
[Required(ErrorMessage = "VAT mandatory.")]
public int VatId { get; set; }
}
Now of course your Save controller action will take the appropriate view model as parameter:
[HttpPost]
public ActionResult Save(SaveCartMvcViewModel model)
{
...
}
And as a side remark, putting the [Required]
attribute on a non-nullable integer property (your VatId
property) hardly makes any sense because a non-nullable integer will always have a value. If you want to validate that the user actually entered some value you'd better use a nullable integer on your view model:
public class SaveCartMvcViewModel
{
public SaveCustomerMvcViewModel Customer { get; set; }
[Required(ErrorMessage = "VAT mandatory.")]
public int? VatId { get; set; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.