How to check if user already exists on client-side in ASP.NET MVC 5?

后端 未结 3 1230
难免孤独
难免孤独 2020-12-09 06:22

Using Visual Studio 2013.4 (Visual Studio 2013 Update 4) I have created a regular ASP.NET MVC 5 project with Individual User Accoun

3条回答
  •  旧巷少年郎
    2020-12-09 07:00

    You could use RemoteAttribute to perform client side validation with a server callback.

    1) Add the following method to the AccountController:

    [AllowAnonymous]
    public async Task UserAlreadyExistsAsync(string email)
    {
        var result = 
            await userManager.FindByNameAsync(email) ?? 
            await userManager.FindByEmailAsync(email);
        return Json(result == null, JsonRequestBehavior.AllowGet);
    }
    

    2) Add Remote attribute to Email property of RegisterViewModel class:

    [Remote("UserAlreadyExistsAsync", "Account", ErrorMessage = "User with this Email already exists")]
    public string Email { get; set; }
    

    where "Account" is the name of the serving controller and "UserAlreadyExistsAsync" is it's action name.

提交回复
热议问题