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
- 发表评论
-
- 最新评论 进入详细评论页>>
今日头条
更多>>您可能感兴趣的文章
- Pro ASP.NET MVC 3 Framework学习笔记之九
- winform下通过webclient使用非流方式上传(post)数据和
- 教你如何来恢复一个丢失的数据文件
- asp.net 六大内置对象(2)
- Asp.net MVC源码分析--Model Validation(Client端)实现(2)
- 微软ASP.NET站点部署指南(11):部署SQL Server数据
- 谈.Net委托与线程——创建无阻塞的异步调用(一
- MVC中一个表单实现多个提交按钮(一个action搞定
- ASP.NET数据格式的Format--DataFormatString
- asp.net js模拟Button点击事件