0

I'm trying to expand beyond the "one-to-one" mapping of models to controllers to views that most mvc(3) tutorials offer.

I have models for a person (operator) and the person's picture. In the database they would correspond to Operator and OperatorPicture tables.

public class Operator
{

    public Operator()
    {
        this.OperatorPictures = new HashSet<OperatorPicture>();
    }

    [DisplayName("Operator ID")]
    public int OperatorID { get; set; }

    [Required]
    [DisplayName("First name")]
    [StringLength(20, ErrorMessage = "The first name must be 20 characters or less.")]
    public string OperatorFirstName { get; set; }

    [Required]
    [DisplayName("Last name")]
    [StringLength(20, ErrorMessage = "The last name must be 20 characters or less.")]
    public string OperatorLastName { get; set; }

    public virtual ICollection<OperatorPicture> OperatorPictures { get; set; } // Nav
}

public class OperatorPicture
{

    [DisplayName("Operator Picture ID")]
    public int OperatorPictureID { get; set; }

    [DisplayName("Operator ID")]
    public int OperatorID { get; set; }

    [DisplayName("Picture")]
    public byte[] Picture { get; set; } // 100x100

    [DisplayName("Thumbnail")]
    public byte[] Thumbnail { get; set; } // 25x25

    public virtual Operator theoperator { get; set; } // FK

}

In most views I would present them together. A list of operators would include a thumbnail picture if it exists. Another screen might show the person's detailed information along witht the full-sized picture.

Is this where viewmodels come into play? What is an appropriate way to use them?

Thanks, Loyd

logo1664
  • 23
  • 4

1 Answers1

0

Definitely a time for using them. ViewModels are just a way of packaging up all the different bits that go into a view or partialview.

Rather than have just the repository pattern, I have repositories and services. The service has a Get property called ViewModel, that can be called from the controller. EG:

// initialise the service, then...
return View(service.ViewModel)

You can see a more detailed description of my approach in the accepted answer for the following SO question:

MVC Patterns

Note that I am using dependency injection in that code.

It may not be a totally orthodox or canonical approach, but it results in very clean controller code and a easy to use pattern.

Community
  • 1
  • 1
awrigley
  • 13,481
  • 10
  • 83
  • 129