我不明白为什么模型绑定不验证数据。我的代码工作正常,没有模型联编程序。我试图调用的操作是Enter。所以,网址是这样的。 (本地主机:5×10 17 /客户/输入)。我的代码如下。为什么数据注解与asp.net MVC5中的model-binder不起作用?
客户Controller.cs
public class CustomerController : Controller
{
// GET: Customer
public ActionResult Load()
{
Customer obj = new Customer()
{
CustomerCode = "1001",
CustomerName = "Rezwan"
};
return View("Customer", obj);
}
public ActionResult Enter()
{
return View("EnterCustomer");
}
public ActionResult Submit([ModelBinder(typeof(CustomerBinder))] Customer obj)
{
if (ModelState.IsValid)
return View("Customer", obj);
else
return View("EnterCustomer");
}
}
EnterCustomer.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="txtCustomerName" type="text" />
Customer Code - <input name="txtCustomerCode" type="text" />
<input id="Button1" type="submit" value="submit" />
</form>
@Html.ValidationSummary()
</div>
</body>
</html>
个Customer.cs
public class Customer
{
[Required]
[RegularExpression("^[A-Z]{3,3}[0-9]{4,4}$")]
public string CustomerCode { get; set; }
[Required]
[StringLength(10)]
public string CustomerName { get; set; }
}
CustomerBinder.cs
public class CustomerBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpContextBase objContext = controllerContext.HttpContext;
string CustCode = objContext.Request.Form["txtCustomerCode"];
string CustName = objContext.Request.Form["txtCustomerName"];
Customer obj = new Customer()
{
CustomerCode = CustCode,
CustomerName = CustName
};
return obj;
}
}
Customer.cshtml
@model HelloWorld.Models.Customer
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Customer</title>
</head>
<body>
<div>
Name - @Model.CustomerName <br/>
Code - @Model.CustomerCode
</div>
</body>
</html>
请帮我一把。我是新的asp.net语言。
如果你在'CustomerBinder.BindModel'中放置了一个断点,那么这个代码是否被命中? – DiskJunky
您是否启用了不显眼的客户端验证? –
你说你试图调用控制器动作输入,但你的表单在EnterCustomer.cshtml映射到提交动作 – Fran