Search code examples
c#asp.net-mvcasp.net-mvc-viewmodel

asp.net mvc - nearly identical ViewModels


I am building a web application with ASP.NET MVC and am still a beginner with this technology.

I have learned that it is best practice to have a ViewModel for each View. I can understand why this is a good idea. However, in my situation it seems to create a lot of extra work.

I have a model called Rule. It contains an Id, Title, Description, LastModifiedDate, CreatedDate, among other fields.

I have an Edit, Create and Details view for the Rule model.

According to the best practice, I have to make a ViewModel for each of the above Views. But the ViewModels for above Views are nearly identical. One of the only differences is that the Create-ViewModel has no Id, but the Details and Edit ViewModels do. Other than that, the ViewModels are nearly identical. That is, they contain the same attributes and same DataAnnotation validation fields.

Why do I think this is troublesome? Suppose I want to change some of the Data Annotations. E.g. chaneg a Maximum Length of a string attribute. If I wish to do so, I have to do so in both the Rule model, the Create ViewModel and Edit ViewModel. And likewise if I wish to add new attributes, I must do so in all the models.

Am I doing this right, or can it be simplified?


Solution

  • Well this is more an implementation decision rather than a best practice rule. You have to take in consideration some of the pros and cons:

    Different ViewModel for each view

    • Modify only the ViewModel associated with the view
    • Flexibility
    • Hard to maintain with very large applications

    Reuse ViewModels for different views

    • Modify all the ViewModels at once
    • Much easier to maintain
    • Limited flexibility

    My advice would be to create the base RuleViewModel without the ID property and for the edit and details actions inherit the model and add the additional column.