What is the recommended place to check: ViewModel, Model or Controller?

I have a registration page and you want to do some verification (in addition to StringLength and Required annotations on my ViewModel) to duplicate usernames and email addresses. I am currently doing this check in my controller when the registration form is sent back. I am not sure if this is the right place for this.

I cannot imagine that the ViewModel is the right place, since the ViewModel will need a link to my UserRepository. Does it make sense to have such validation in model classes?

If so, how to implement this on a model to check if the information is valid before I sent it to my repository?

Update

My controller action code:

if (ModelState.IsValid)
        {
            if (!_userRepository.Exists(registerViewModel.Username))
            {
                if (!_userRepository.EmailExists(registerViewModel.Email))
                {
                    _userRepository.Add(
                        new User
                            {
                                Created = DateTime.Now, 
                                Email = registerViewModel.Email, 
                                Password = registerViewModel.Password, 
                                Username = registerViewModel.Username
                            });

                    _userRepository.SaveChanges();
                    TempData["registrationDetails"] = registerViewModel;

                    return RedirectToAction("Confirm");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "This email address is already in use.");
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, "This username is already taken.");
            }
        }

        return View(registerViewModel);
    }

2

, , , ?

3

, , submit. - , ?

,

+3
5

, .

, , Ajax , . , .

, ajax-ly , .

, , (UI ), .

, , Javascript, knockoutjs . MVVM, ViewModels, ( ), . , .

0

frontend (, ajax), - .

, . / - dup - ( ajax ).

: MVVM ( ) Windows. MVC MVVM

+1

, . ( ViewModels, ), , , , . , , ViewModels . , .

0

- , , , .

-

for MVC3, you can add methods to the controller as actions using the Remote attribute in your property in the view model for instant results

0
source

You should check both on the view (on the client side) and on the controller (on the server side). If you have MVC 3, you can use the new RemoteAttribute . It uses jQuery for a server-side call where you can check for a user or email address.

0
source

Source: https://habr.com/ru/post/1795660/


All Articles