ModelState

public ActionResult Index(string UserName, string Email, string Password, string confirmPassword) 

{ 

  ViewData["title"] = "用户注册"; 

if (String.IsNullOrEmpty(UserName)) 
    { 
    ModelState.AddModelError("UserName", "用户名不能为空"); 
    } 

string email="^[a-zA-Z][a-zA-Z0-9._-]*@([a-zA-Z0-9-_]+\.)+(cn|com|gov|net|com\.cn|edu\.cn)$"; 

if (String.IsNullOrEmpty(Email) || !Regex.IsMatch(Email, email)) 
    { 

    ModelState.AddModelError("Email", "邮箱不能为空或格式不对"); 

    } 

if (Password == null || Password.Length<= 6) 

    { 

    ModelState.AddModelError("Password", "密码不能为空或长度不能小于6位"); 

    } 

if (!String.Equals(Password, confirmPassword)) 

    { 

ModelState.AddModelError("_FORM", "两次密码不一致"); 

    } 

if (ViewData.ModelState.IsValid) 
    {//验证通过则进行相应的动作
    Return Redirect("Error.html");
    } 

return View(); 

}

 

在action里面给用于验证的ModelState绑定数据,就可以在页面中访问了。

原文地址:https://www.cnblogs.com/wllhq/p/4606823.html