Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing viewdata to asp.net mvc masterpages

I'm trying to pass ViewData to my asp.net mvc masterpage for an mvc usercontrol that I keep on a masterpage. For example, I created a dropdownlist of names as an mvc usercontrol and I put that in my masterpage.

The problem I am running into is passing the ViewData to the masterpage. I found this article from Microsoft which has a decent solution but I was wondering if there are other "better" solutions out there. The thing I don't like about the solution in the link is that I have to change every controller to inherit from a new controller class.

http://www.asp.net/learn/MVC/tutorial-13-cs.aspx

Edit: The problem I am looking at is the fact that if I place a user control in my masterpage that relies on ViewData, I have to REPEATEDLY include that ViewData for every single page that uses said masterpage. It's possible the solution in the link above is the best solution but I was hoping there were other alternatives.

like image 929
codette Avatar asked Mar 31 '09 07:03

codette


3 Answers

The master page already has access to the ViewData. If you want strongly typed access to it, you need to do two things:

  1. Put the master page stuff in a base class (e.g. CommonViewData)
  2. Have you master page inherit from the generic ViewMasterPage<> class:

    " %>
like image 65
James L Avatar answered Oct 19 '22 23:10

James L


Could you possibly use the OnActionExecuting method on a base controller class and populate the view data there?

Something like:

protected override void OnActionExecuting(ActionExecutingContext context)
{
  context.Controller.ViewData.Model = GetDataForControl();
}

I haven't tried it so it's just a thought...

like image 43
Gil Avatar answered Oct 19 '22 22:10

Gil


For what it's worth, I am using the method from that tutorial in a current project and it works very well.

What you can also do, if it is data that is somewhat static (like a menu that doesn't change much), is to put the object on the cache so your database isn't called for every controller initialisation.

like image 23
Morph Avatar answered Oct 20 '22 00:10

Morph