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
- 发表评论
-
- 最新评论 进入详细评论页>>
今日头条
更多>>您可能感兴趣的文章
- .Net Remoting与WCF实现Server与Client通讯比较
- asp.net使用httphandler打包多CSS或JS文件以加快页面加
- ASP.NET 2.0编程小技巧两则
- ASP.NET中Request.InputStream使用
- .NET中序列化(二)
- 实现.net cms系统 第三篇《大刀阔斧-核心源码》
- 【译】MVC3 20个秘方-(13)使用Ajax Helper 提高用户
- Asp.net MVC源码分析--Model Validation(Server端
- wcf系列5天速成——第一天 binding的使用(1)
- winform下通过webclient使用非流方式上传(post)数据和