TryValidateModel不分配对象,返回所有空值,MVCStore示例

时间:2013-02-17 20:16:56

标签: asp.net-mvc asp.net-mvc-4 data-annotations

在Checkout Controller中我有代码

    [HttpPost]
    public ActionResult AddressAndPayment(FormCollection values)
    {
        var order = new Order();
        TryValidateModel(order);
     ....

模型看起来像这样

[Bind(Exclude="OrderId")]
public partial class Order
{
    [ScaffoldColumn(false)]
    public int OrderId { get; set; }

    [ScaffoldColumn(false)]
    public string Username { get; set; }

    [Required(ErrorMessage= "First Name is required")]
    [DisplayName("First Name")]
    [StringLength(160)]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name is required")]
    [DisplayName("Last Name")]
    [StringLength(160)]
    public string LastName { get; set; }

    [Required(ErrorMessage="Address is required")]
    [StringLength(70)]
    public string Address { get; set; }

    [Required(ErrorMessage = "City is required")]
    [StringLength(40)]
    public string City { get; set; }

    [Required(ErrorMessage = "State is required")]
    [StringLength(40)]
    public string State { get; set; }

    [Required(ErrorMessage = "Postal Code is required")]
    [DisplayName("Postal Code")]
    [StringLength(10)]
    public string PostalCode { get; set; }

    [Required(ErrorMessage="Country is required")]
    [StringLength(40)]
    public string Country { get; set; }

    [Required(ErrorMessage= "Phone is required")]
    [StringLength(24)]
    public string Phone { get; set; }

    [Required(ErrorMessage="Email Address is required")]
    [DisplayName("Email Address")]
    [RegularExpression(@"[A-za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage="Email is not valid.")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [ScaffoldColumn(false)]
    public decimal Total { get; set; }

    [ScaffoldColumn(false)]
    public DateTime OrderDate { get; set; }
    public List<OrderDetail> OrderDetails { get; set; }
}

我可以在TryValidateModel行之前停止并查看表单值,如

? Request.Form["FirstName"]
 "Michael"
 ? values["FirstName"]
   "Michael"

那么为什么TryValidateModel(订单);返回false并且订单对象没有填充?

更新 为了澄清我的问题我知道错误意味着它不能绑定但我不知道为什么它不能绑定。或者它应该通过TryValidateModel(甚至是ValidateModel)

但有趣的是,如果我将方法签名更改为

 public ActionResult AddressAndPayment(Order order)

订单正确填充。那么如果能够在Method调用中绑定为什么不是TryValidateModel(甚至是ValidateModel)?

我正在使用MVC 4

1 个答案:

答案 0 :(得分:1)

TryValidateModel针对您的false验证失败时,

Form Model会返回Orders Model,因此绑定失败。

我讨厌使用

TryValidateModel(order);

并且更喜欢

    ValidateModel(order);

在开发我的页面的早期,因为绑定是一个微妙的过程。这样,如果模型无法绑定,我会收到异常和指示性错误信息。