控制器动作:
[AjaxRequestOnly, HttpPost, Authorize]
public ActionResult AddCreditCard(CustomerCreditCardModelView cc) {
if (!ModelState.IsValid) {
Response.StatusCode = 400;
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(ModelState.Values.SelectMany(v => v.Errors).Select(e=>e.ErrorMessage)));
}
// .... do something ...
}
模型视图:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using CheckoutVC.CheckoutServiceReference;
using Newtonsoft.Json;
public class CustomerCreditCardModelView {
[Display(Name = "Número")]
[Required(ErrorMessage = "El Número es requerido")]
[StringLength(20, MinimumLength = 12, ErrorMessage = "El número parece ser incorrecto")]
[JsonIgnore, ScriptIgnore]
public string CardNumber { get; set; }
[Display(Name = "Código de seguridad")]
[Required(ErrorMessage = "El Código de seguridad es requerido")]
public string CardSecurityCode { get; set; }
[Display(Name = "Nombre en la tarjeta")]
[Required(ErrorMessage = "El Nombre en la tarjeta es requerido")]
public string NameOnCard { get; set; }
[Display(Name = "Dirección de cobro")]
[Required(ErrorMessage = "La Dirección de cobro es requerida")]
public string BillingAddress { get; set; }
[Display(Name = "Mes de vencimiento")]
[Required(ErrorMessage = "El Mes de vencimiento es requerido")]
public int ExpirationMonth { get; set; }
[Display(Name = "Año de vencimiento")]
[Required(ErrorMessage = "El Año de vencimiento es requerido")]
public int ExpirationYear { get; set; }
[Display(Name = "Documento")]
[Required(ErrorMessage = "El documento es requerido")]
public string Document { get; set; }
[Display(Name = "Tipo de tarjeta")]
public int IdCreditCard { get; set; }
public int IdCustomer { get; set; }
public bool IsDeleted { get; set; }
public int IdCustomerCreditCard { get; set; }
public CustomerCreditCardModelView() {
}
请求有效载荷:
{"idCreditCard":1,"nameOnCard":"fdsa","billingAddress":"fdsa"}
请求响应:
["El Número es requerido","El Código de seguridad es requerido","El documento es requerido"]
如您所见,除了 int ExpirationMonth 和 int ExpirationYear 应该返回验证错误(必需)之外,一切都运行良好,但它们没有。
实际上,modelstate 只有 6 个键....
什么可能导致这种行为?我想 expireMonth 和 expirationYear 考虑到 [Required] DataAnnotation 属性。
很确定这里发生了同样的事情:mvc model validation required not working on all fields
编辑:阅读对该问题的评论,发现问题出在使用上,而不是我的情况。我包括了使用部分。