BrightonDev
BrightonDev

Reputation: 435

MVC ViewModel scope

This may be a matter of taste but when creating ViewModels is it best practice to go with multiple public classes like below (bear in mind these 3 classes are servicing just a single view):

namespace WebApp.Areas.Commerce.Models.ViewModels
{
    public class TravellersViewModel
    {
        public TicketHolder TicketHolder { get; set; }
        public List<Traveller> TicketMembers { get; set; }
        public int MaxAge { get; set; }
        public bool ShowAddress { get; set; }
    }

    public class TicketHolder
    {
        public string EmailAddress { get; set; }
        public string TelephoneNumber { get; set; }
        public string MobileNumber { get; set; }
        public string Address1 { get; set; }
        public string Postcode { get; set; }
        public string Country { get; set; }
    }


    public class Traveller
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int? Age { get; set; }
        public bool Policyholder { get; set; }
        public Traveller()
        {
            Title = "Mr";
        }
    }
}

Or is it best to nest the child classes within the scope of the single view model

namespace WebApp.Areas.Commerce.Models.ViewModels
{
    public class TravellersViewModel
    {
        public TicketHolderDetails TicketHolder { get; set; }            
        public List<Traveller> TicketMembers { get; set; }
        public int MaxAge { get; set; }
        public bool ShowAddress { get; set; }

        public class TicketHolderDetails
        {
            public string EmailAddress { get; set; }
            public string TelephoneNumber { get; set; }
            public string MobileNumber { get; set; }
            public string Address1 { get; set; }
            public string Postcode { get; set; }
            public string Country { get; set; }
        }

        public class Traveller
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int? Age { get; set; }
            public bool Policyholder { get; set; }
            public Traveller()
            {
                Title = "Mr";
            }
        }
    }
}

I quite like the second way of building the viewmodel as it keeps everything togther.

Upvotes: 0

Views: 282

Answers (1)

Sir Hally
Sir Hally

Reputation: 2358

My way to make viewmodel is following:

if some class is unique for one ViewModel, it should be nested (there is no reason to access such class from the outside code).

If this class could be used is the different ways (for example, the same entity for different viewmodels), it should be placed separetely.

Upvotes: 1

Related Questions