我刚开始学习MVC,所以这可能是一个愚蠢的问题。
查看数据注释以执行验证,我注意到
ModelState.IsValid
仅当对象在Action中定义如下时,属性名称也必须与输入名称匹配:
客户控制器.cs
public ActionResult Submit(Customer obj) <-- here
{
if (ModelState.IsValid)
{
return View("Customer", obj);
}
else
{
return View("EnterCustomer");
}
}
客户.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始终为真,有人能告诉我为什么吗?
客户控制器.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");
}
}