Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's more than that ;-) You can fetch in model binder or action filter. For the second option, check Jimmy Bogard's blog somewhere around <a href="http://www.lostechies.com/blogs/jimmy%5Fbogard/archive/2009/04/24/how-we-do-mvc.aspx" rel="nofollow noreferrer">here</a>. I personally do it in model binders. I use ViewModel like this: <a href="https://stackoverflow.com/questions/1453641/my-custom-asp-net-mvc-entity-binding-is-it-a-good-solution">My custom ASP.NET MVC entity binding: is it a good solution?</a>. It is processed by my custom model binder:</p> <pre><code>public object BindModel(ControllerContext c, BindingContext b) { var id = b.ValueProvider[b.ModelName]; // don't remember exact syntax var repository = ServiceLocator.GetInstance(GetRepositoryType(b.ModelType)); var obj = repository.Get(id); if (obj == null) b.ModelState.AddModelError(b.ModelName, "Not found in database"); return obj; } public ActionResult Action(EntityViewModel&lt;Order&gt; order) { if (!ModelState.IsValid) ...; } </code></pre> <p>You can also see an example of model binder doing repository access in <a href="http://www.sharparchitecture.net" rel="nofollow noreferrer">S#arp Architecture</a>.</p> <p>As for static data in view models, I'm still exploring approaches. For example, you can have your view models remember the entities instead of lists, and</p> <p>public class MyViewModel { public MyViewModel(Order order, IEmployeesSvc _svc) { } </p> <pre><code> public IList&lt;Employee&gt; GetEmployeesList() { return _svc.GetEmployeesFor(order.Number); } </code></pre> <p>}</p> <p>You decide how you inject _svc into ViewModel, but it's basically the same as you do for controller. Just beware that ViewModel is also created by MVC via parameterless constructor, so you either use ServiceLocator or extend MVC for ViewModel creation - for example, inside your custom model binder. Or you can use Jimmy Bogard's approach with AutoMapper which does also support IoC containers.</p> <p>The common approach here is that whenever I see repetative code, I look to eliminate it. 100 controller actions doing domain-viewmodel marshalling plus repository lookup is a bad case. Single model binder doing it in generic way is a good one.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload