Asp.net MVC源码分析--Model Validation(Server端)实现(1)
一.MVC Validation 用法:
在Asp.net MVC 框架中如果需要对Model 对象加入验证,我们可以在Model的属性上标记所有继承于ValidationAttribute的Attribute特性.
例如下面的代码中,StringLength/Range/Compare 都是继承于ValidationAttribute类.
public class LogOnModel
{
[Required]
[StringLength(10)]
public string UserName { get; set; }
[Required]
[Range(5,10)]
public string Password { get; set; }
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
复制代码
在Action 中我们可以调用 ValidateModel 方法对Model对象进行验证,如果验证没有通过则会抛出InvalidOperationException异常,同时ModelState.IsValid状态为false
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
this.ValidateModel(model);
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
&nb
- 发表评论
-
- 最新评论 进入详细评论页>>
今日头条
更多>>您可能感兴趣的文章
- JQuery+Asp.net MVC实现用户名重名查询
- 使用ASP.NET MVC3+EF+Jquery制作文字直播系统(四
- MVC3+Entity Framework 实现投票系统(二)
- 聊聊.net程序设计——浅谈使用VS2010建模拓展(下
- Web Service学习笔记(4)
- asp.net DataTable和Dataset序列化成Json格式
- .NET设计模式:工厂方法模式(Factory Method)[1]
- Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注
- .NET简谈互操作(四:基础知识之Dispose非托管内存
- .net架构的最后思考(箴言)



