我正在使用远程验证来检查数据库中是否已经存在电子邮件,但它不起作用,这是代码:
模型属性
[Remote("IsAlreadyUserExist", "User", HttpMethod = "POST", ErrorMessage = "Email Already Exists.")]
public string Email { get; set; }
控制器
[HttpPost]
public JsonResult IsAlreadyUserExist(string Email)
{
return Json(IsUserExist(Email));
}
public bool IsUserExist(string Email)
{
List<UserProfile> userlist = userRepo.GetUserList();
var UserEmailId = (from u in userlist
where u.Email.ToUpper() == Email.ToUpper()
select new { Email }).FirstOrDefault();
bool status;
if (UserEmailId != null)
{
//Already registered
status = false;
}
else
{
//Available to use
status = true;
}
return status;
}
我已在底部的“创建”视图中添加了此js。
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
我还尝试将调试器置于IsAlreadyUserExist
函数中,但没有成功。
任何想法可能是什么问题?
答案 0 :(得分:0)
要使RemoteAttibute
有效,请在RemoteAttibute
属性上编写Email
,如下所示:
[Required]
[StringLength(30)]
[Index("Ix_Email",Order =1,IsUnique =true)]
[Remote("IsUserAlreadyExists", "User", AdditionalFields = "Id", ErrorMessage = "User already exists with the provided email")]
public string Email { get; set; }
您正从内存中的数据库中拉出所有用户,只是为了检查某个电子邮件是否已经存在一个用户,考虑到性能,这是非常非常糟糕的。因此,请在IsUserAlreadyExists
中编写UserController
方法,如下所示:
public JsonResult IsUserAlreadyExists(string Email, int? Id)
{
var isUserAlreadyExists = db.Users.Any(x => x.Email== Email && x.Id != Id);
return Json(!isUserAlreadyExists, JsonRequestBehavior.AllowGet);
}
现在,如果要将数据库访问代码移至UserRepository
,请按以下步骤进行操作:
public class UserRepository
{
YourDbContext dbContext = new YourDbContext();
public bool IsUserAlreadyExistsByEmail(string email, int? id)
{
return dbContext.Users.Any(x => x.Email== Email && x.Id != Id);
}
}
然后按如下所示调用IsUserAlreadyExistsByEmail
的{{1}}方法:
UserRepository
注意:我没有看到您的存储库代码,因此在这里显示了它应该是如何的通用视图。根据自己的结构使用一切。