1

I see the following design in the code which is part of the default web application project in visual studio:

A single data model class in constructed and decorated with various data validation annotations. For Example, there's a RegisterViewModel class that looks like this:

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

This class then serves two purposes:

  1. It is the 'view model' or the type for the view which consists of the html form with which the user registers. The html details as well as the jquery validation metadata can be automatically extracted from the class's data annotations.
  2. When the user posts his/her form back to the server, the form data is stored in an object of the same type; e.g. in this case the Register action signature looks like this:

    public async Task<ActionResult> Register(RegisterViewModel model)

Among other things, this allows for server-side validation to happen using the same data annotations.

Is this a common, acceptable pattern? Is it a design to strive for when building my own forms?

-1

Well, I don't see anything unusual here. ViewModel validation is a common thing. Although I would say, that domain entity should also be validated. Here is a good article on the subject.

-1

The ViewModel that you show is a model that is intended to be used with a view. As such, it has facilities for helping to display the data and facilities for helping to receive the data.

In very small applications, you could consider using that data structure as your primary data model.

However, in serious applications, you wouldn't model your data that way. Among other things, you should have only one password stored in your repository, and, more importantly, you would store passwords separately from user specific data and it must be encrypted. In other words, the ViewModel is a representation of your underlying business model for the purposes of interacting with the user, and not the same as your business model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.