1

I have question about fetching data in view model.

For example i have viewmodel :

public class EmployeeCreateVM
{
    public Employee Employee { get; set; }
    public List<EmployeeState> EmployeeStates { get; set; } // dropdownlist data
    public List<EmployeeType> EmployeeTypes { get; set; } // dropdownlist data

    public EmployeeCreateVM()
    {
        EmployeeStates = ...
        EmployeeType = ...
    }
}

My question is about design view model, specially fetching data. For my current project, i am fetching data from controller for example :

[Get]
EmployeeCreateVM model = new EmployeeCreateVM();
model.EmployeeStates = _repository....

[Post] - again
model.EmployeeStates = _repository....

Is bad practice to fetch data directly from view model class?

Thanks

Mennion
  • 2,873
  • 3
  • 20
  • 34

1 Answers1

1

Yes, as it violates the separation of concerns. If you later needed to change the data access methodology, it would no longer be in a single place (controller) but in each and every view model using that repository.

There is more discussion here: What to put in your ViewModel

Community
  • 1
  • 1
Shawn
  • 1,871
  • 2
  • 21
  • 36
  • Thanks for interesting link. In my application i use DI, so if i change data access methodlogy, i just write other implementation my repository class and set it in di configi – Mennion Jan 11 '12 at 13:53
  • 1
    @Mennion Even so, you should not have that in the constructor; the view model (as well as all classes) should do one thing. Imagine you only wanted to return certain `EmployeeTypes` to your controller/view, this would require you to edit your `EmployeeCreateVM` class, which feels wrong. – wal Jan 11 '12 at 14:07
  • @Wal - yes, fetching data in vm class is unnatural for me. But i like DRY principle and fetching vm in get and post action is not DRY... – Mennion Jan 11 '12 at 14:23
  • @Mennion What are you repeating in your get and post actions? I suggest moving the duplicated code into `EmployeeViewModelRepositoryService` class or similar. – wal Jan 11 '12 at 14:34
  • 1
    @Mennion I agree. I typically use a similar service model that caches the respective dropdownlist data so that when I need to reinflate the viewmodel in cases where the POST model is invalid I don't even have to hit the repository. – Shawn Jan 11 '12 at 14:42
  • @wal Because if model is not valid in post action, i am return model back to view and filling dropdownlists again... – Mennion Jan 11 '12 at 14:49