ModelState.IsValid 仅在定义对象时才起作用?

ModelState.IsValid only when defining object in action?

我刚开始使用 MVC,所以这可能是个愚蠢的问题。

通过数据注释来执行验证,我注意到 ModelState.IsValid 仅当对象在如下 Action 中定义时才有效,而且 属性 名称必须与输入名称匹配:

CustomerController.cs

public ActionResult Submit(Customer obj) <-- here
{
    //Customer obj = new Customer();
    //obj.CustomerName = Request.Form["CustomerName"];
    //obj.CustomerCode = Request.Form["CustomerCode"];

    if (ModelState.IsValid)
    {
         return View("Customer", obj);
    }
    else
    {
         return View("EnterCustomer");
    }            
}

Customer.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MyFirstWebApp.Models
{
    public class Customer
    {
        [Required]
        [StringLength(10)]
        public string CustomerName { get; set; }

        [Required]
        [RegularExpression("^[A-Z]{3,3}[0-9]{4,4}$")]
        public string CustomerCode { get; set; }
    }
}

输入Customer.cshtml

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>EnterCustomer</title>
</head>
<body>
    <div> 
        <form action="Submit" method="post">
            Customer Name: <input name="CustomerName" type="text" /> <br />
            @Html.ValidationMessageFor(x => x.CustomerName) <br />
            Customer Code: <input name="CustomerCode" type="text" /> <br />
            @Html.ValidationMessageFor(x => x.CustomerCode) <br />
            <input id="Submit1" type="submit" value="submit" />
        </form>
    </div>
</body>
</html>

但是,如果我如下定义 obj,当我输入无效值以执行验证时,ModelState.IsValid 始终为真,有人能告诉我为什么吗?

CustomerController.cs

public ActionResult Submit()
{
    Customer obj = new Customer();
    obj.CustomerName = Request.Form["CustomerName"];
    obj.CustomerCode = Request.Form["CustomerCode"];

    if (ModelState.IsValid)
    {
         return View("Customer", obj);
    }
    else
    {
         return View("EnterCustomer");
    }            
}

您可以在 Controller 中使用 TryValidateModel 来验证模型。

Customer obj = new Customer();
obj.CustomerName = Request.Form["CustomerName"];
obj.CustomerCode = Request.Form["CustomerCode"];

if (TryValidateModel(obj))
{
     return View("Customer", obj);
}
else
{
     return View("EnterCustomer");
}