I’m searching for a good way for managing my view models and especially the classes used in these view models. I explain below with an example:
Let’s say I would like to display a view which contains a project (title, content, category, …) and below it a list of some related projects (of the same category). I created a view model especially for this view. Here it is:
public class ProjectDetailsViewModel
{
public ProjectFullViewModel OneProject { get; set; }
public IEnumerable<ProjectLightViewModel> RelatedProjects { get; set; }
// Below are the classes used in this view model
public class ProjectFullViewModel
{
public int ProjectID { get; set; }
public string Title { get; set; }
public string Slug { get; set; }
public string Category { get; set; }
public string Client { get; set; }
public int Year { get; set; }
public IEnumerable<Technology> Technologies { get; set; }
public byte[] ScreenshotData { get; set; }
public string ScreenshotName { get; set; }
public int ScreenshotLength { get; set; }
public string ScreenshotType { get; set; }
public byte[] BackgroundData { get; set; }
public string BackgroundName { get; set; }
public int BackgroundLength { get; set; }
public string BackgroundType { get; set; }
}
public class ProjectLightViewModel
{
public int ProjectID { get; set; }
public string Title { get; set; }
public string Slug { get; set; }
public string Category { get; set; }
public string Client { get; set; }
public string Year { get; set; }
}
}
As you can see, all classes used in this view model are contained in it. I think this is easier to keep en eye on what is used. What do you think? Is it a good/bad practice? Some suggestions? I noticed that when we have a lot of view models and classes used we can be a little confused. Don’t blame me, I’m still learning ASP.NET MVC and I would like to make good choices…
Thanks.
I wouldn’t use nested classes for view models. In order to reference them you will have to always specify the base class. That’s could be particularly annoying when writing the mappings between your domain models and view models. If you are afraid of having many files containing your view models you could still place all the dependent view models inside the same
.csfile as the parent model.