Modelstate的数据验证
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
<% using (Html.BeginForm("Index","Home",FormMethod.Post))
{ %>
<li><input type="text" name="name" id="name" /><%=Html.ValidationMessage("name")%>
</li>
<li><input type="password" name="password" id="password" /></li>
<li><input type="submit" value="提交" name="sub" id="sub" /></li>
<%:ViewData["msg"] %>
<%} %>
</div>
</body>
</html>
[AcceptVerbs("POST")] public ActionResult Index(Models.UserModel model) { if (model != null) { if (string.IsNullOrEmpty(model.Name)) { ModelState.AddModelError("Name", "名称不能为空"); } else if (model.Name.Length > 20) { ModelState.AddModelError("Name", "名称长度不能大于20"); } } if (ModelState.IsValid) { //如果没错误 } else { //如果有错误 } return View(model); }
简单的验证就好了