[英]Bypass required attribute in ASP.NET MVC
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
. 控制器中的Save
方法将收到模型类型CartMvc
。 The problem is, in this case, I don't want validate the property type CustomerMvc
but only VatId
. 问题是,在这种情况下,我不想验证属性类型CustomerMvc
而只能验证VatId
。
Is there a way to bypass, in this case, the validation on CustomerMvc
? 在这种情况下,有没有办法绕过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: 当然,现在,您的Save controller动作将采用适当的视图模型作为参数:
[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. 另外,将[Required]
属性放在不可空的整数属性(您的VatId
属性)上几乎没有任何意义,因为不可空的整数将始终具有值。 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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.