Where to put master page's code in an MVC application?
Asked Answered
C

3

8

I'm using a few (2 or 3) master pages in my ASP.NET MVC application and they must each display bits of information from the database. Such as a list of sponsors, current fundings status etc.

So my question was, where should I put these master-page database calling code?

Normally, these should goes into its own controller class right? But then that'd mean I'd have to wire them up manually (e.g. passing ViewDatas) since it is out of the normal routing framework provided by the MVC framework.

Is there a way to this cleanly without wiring ViewData passing/Action calls to master pages manually or subclassing the frameworks'?

The amount of documentation is very low... and I'm very new to all this including the concepts of MVC itself so please share your tips/techniques on this.

Cuttlebone answered 13/9, 2008 at 13:5 Comment(0)
S
5

One way to do this is to put in the masterpage view the hook for the ViewData and then you define a BaseController : Controller (or multiple base classes) where you do all the db calls you need.

What you wanna do is quite the same thing described in this articles.

I hope this helps!

Regards

Squalid answered 13/9, 2008 at 14:19 Comment(0)
T
1

Great question. You have several options available to you.

  1. Have a jQuery call on your masterpage that grabs the data you need from a controller and then populate your fields using jQuery again.
  2. Your second option is to create user controls that make their own calls to the controller to populate their information.

I think the best choice is creating controls for the region of your masterpage that has data that needs to be populated. Thus leaving your masterpage to strictly contain design elements. Good luck.

Thrice answered 12/2, 2009 at 19:56 Comment(0)
Q
0

If you don't mind strongly typed view data, you can put all the master page data in a common base class for viewData. You can set this data in the base class's constructor. All your views requiring additional data will then need strongly typed viewdata that inherits from this base class.

To allow a call to View() in your controllers without any explicit viewdata you can override View in your ControllerBase:

protected override ViewResult View(string viewName, string masterName, object model)
{
    if (model == null)
    {
        model = new ViewDataBase();
    }
    return base.View(viewName, masterName, model);
}
Quota answered 15/9, 2008 at 20:49 Comment(1)
Might wanna call that BaseViewData instead :-)Cuttlebone

© 2022 - 2024 — McMap. All rights reserved.