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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

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 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 - 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 What are you repeating in your get and post actions? I suggest moving the duplicated code into EmployeeViewModelRepositoryService class or similar.
@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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.