MVC Architecture - Reuse the same view model for reading and editing

Say we have the following (overly simple) scenario:

We have a screen for viewing information about a person and a screen for editing information about a person.

Information about personalizing the screen has the following fields (display only):

First Name Last Name Bio

The following fields display information about personalizing the screen (in input controls):

Identifier (hidden) First name Last name Bio

Suppose our display model looks like this:

    public class DisplayPersonViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Bio { get; set; }
    }

And our viewmodel edition looks like this:

public class EditPersonViewModel
{
    [Required]
    public int ID { get; set; }

    [Required]
    [StringLength(20)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(20)]
    public string LastName { get; set; }

    [Required]
    public string Bio { get; set; }
}

Not a big difference between the two, huh? The editing model has one additional field (ID) and some property attributes. Now, if we combined 2 as follows:

    public class DisplayPersonViewModel
    {
        [Required]
        [StringLength(20)]
        public string FirstName { get; set; }

        [Required]
        [StringLength(20)]
        public string LastName { get; set; }

        [Required]
        public string Bio { get; set; }
    }

    public class EditPersonViewModel : DisplayPersonViewModel
    {
        [Required]
        public int ID { get; set; }
    }

, , DRY, , () . , , 25 ! (... - , , , :)...) , , " ".

+5
2

, . , , , . , , , .

, , FluentValidation.NET, , , , . , , 2 , EditPersonViewModel - DisplayPersonViewModel, EditPersonViewModelValidator EditPersonViewModel .

: [Required] . . :

[Required]
public int ID { get; set; }

:

public int ID { get; set; }
+4

- MetadataType.

public class PersonModel
{
  public int ID { get; set; }   
  public string FirstName { get; set; }  
  public string LastName { get; set; }   
  public string Bio { get; set; }   
}

[MetadataType(typeof(IDisplayPersonViewModel))]
public class DisplayPersonViewModel : PersonModel

[MetadataType(typeof(IEditPersonViewModel))]
public class EditPersonViewModel : PersonModel

public interface IDisplayPersonViewModel
{
  [ScaffoldColumn(false)]
  public int ID { get; set; }   
}

public interface IEditPersonViewModel
{
  [Required]                
  [StringLength(20)]                
  public string FirstName { get; set; }                

  [Required]                
  [StringLength(20)]                
  public string LastName { get; set; }                

  [Required]                
  public string Bio { get; set; }                

  [Required]                
  public int ID { get; set; }             
} 

Person . , .

+1

All Articles