在MVC 3创建自定义数据注解验证 [英] Creating custom data annotation validation in MVC 3

查看:116
本文介绍了在MVC 3创建自定义数据注解验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举例来说,我有一个员工视图模型。当创建一个员工,我要验证的用户名,以确保它不存在。

For instance, I have an Employee view model. When creating an employee, I want to validate the username to make sure it doesn't exist.

public class EmployeeViewModel
{
    [ScaffoldColumn(false)]
    public int EmployeeId { get; set; }

    [ValidateDuplicate(ErrorMessage = "That username already exists")]
    [Required(ErrorMessage = "Username is required")]
    [DisplayName("Username")]
    public string Username { get; set; }
}

再有我ValidateDuplicate功能某处与code,检查是否有重复的。

And then have my ValidateDuplicate function somewhere with the code to check for a duplicate.

这可能吗?

推荐答案

我建议在看<一个href=\"http://davidhayden.com/blog/dave/archive/2011/01/04/ASPNETMVC3RemoteValidationTutorial.aspx\">remote验证。中的例子,即使符合你的情况。

I would suggest looking at remote validation. The example even matches your case.

基本上,远程属性添加到您的视图模型属性指向一个控制器动作

Basically, add the remote attribute to your viewmodel property that points to a controller action

[Remote("IsUserExists", "Account", ErrorMessage = "Can't add what already exists!")]
[Required(ErrorMessage = "Username is required")]
[DisplayName("Username")]
public string Username { get; set; }

该做的工作。

public ActionResult IsUserExists(string userName) 
{
 if (!UserService.UserNameExists(userName) || (CurrentUser.UserName == userName))
 {
      return "Ok.";
 }
}

这篇关于在MVC 3创建自定义数据注解验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆