Modelstate的数据验证

 
    
<% @ Page Language = " C# " Inherits = " System.Web.Mvc.ViewPage " %>

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 >
利用ModelState来判断

 [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);


            
        }

简单的验证就好了

转载于:https://www.cnblogs.com/linjiancun/archive/2010/10/09/1846359.html

你可能感兴趣的:(xhtml,c#,测试)