开发者

MVC3 load common data for views

I am developing an MVC3 "movie list" application containing several "sites" depending on the request hostname.

I am trying to use a strongly typed ViewModel like this (examples are simplified to get to the essence of the question):

class ViewModelB开发者_运维知识库ase
{
  public int siteId { get; private set; }

  public ViewModelBase(DbContext db)
  {
    siteId = <here I want to make a db-lookup based on the request hostname> <== This is my problem
  }
}

class MoviesIndexViewModel : ViewModelBase
{
  public List<Movie> movies { get; private set; }

  public MoviesIndexViewModel(DbContext db) : base(db)
  {
    movies = db.Movies.where(m => m.SiteId == siteId).ToList();
  }
}

An my controller would then just do this:

public class MoviesController : Controller
{
  public ActionResult Index()
  {
    var model = new MoviesIndexViewModel(new MySpecialDbContext());
    return View(model);
  }
}

Question is: How will I get the "request host header" into the code line shown above? I know how to make the actual DB-lookup, but can I just access any request parameters here? Or should I supply something through parameters to the constructor?


I would not use Dbcontext in my view models. Read about Separation of concerns

Instead, use OnResultExecuting in your BaseController to add the common data:

protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
    var baseModel = filterContext.Controller.ViewData.Model as YourCustomModel;
    if (baseModel != null)
    {
        // call a repository or whatever to add information to the model.
    }

    base.OnResultExecuting(filterContext);
}

Update

yes. The controller is the glue between the "model" (repositores, webservices or any other data source) and the view. The ViewModel is just an abstraction to move away logic from the view.

Here is the three main reasons you should use a view model: http://blog.gauffin.org/2011/07/three-reasons-to-why-you-should-use-view-models/

And an alternative approach to handle common view data: http://blog.gauffin.org/2011/09/getting-information-into-the-layout-without-using-viewbag/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜