Just getting started with MVC, long-time WebForms experience.
I don't want to decorate my entities with UI-oriented properties like "display name" or "required", plus a lot of them have more methods and properties than I care to expose on a view.
So I'm experimenting with ViewModels that wrap, or in other ways interact with the actual entities in my system. What I don't like is how the Controller has to know to query a repository and then instantiate a ViewModel to wrap the entity it got back.
What are best-practices for a controller to interact with ViewModels without having to know how they're persisted? All the examples I see talk directly to EntityFramework or other ORM's.
I was thinking about static methods on the ViewModel classes that take an IRepository reference and an ID to load and return the ViewModel. Does that make sense?
Use DependencyInjection to pass your Repository to your controller.
public HomeController
{
private readonly IHomeRepository repo;
public HomeController(IHomeRepository repository)
{
repo = repository;
}
}
Then inside your action methods, get the items, and create your ViewModels from those objects.
public ActionResult Index()
{
// IEnumerable models are bad, but this is just a quick demo.
var viewModels = repo.GetWidgets().Select(w => new WidgetModel(w));
return View("Index", viewModels);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With