views:

122

answers:

1

i have user control, which i render on several views. i want to show viewdata in the usercontrol, but viewdata must be filled in controller method, so i need to fill viewdata on each controller method of each view, where i render usercontrol. is there any simple solutions?

+2  A: 

Have a controller for that control like

MenuController

with an action method

RenderMenu()
{
    **do your work to get the data here and preferrably strong type it**
    return PartialView("NameOfYourAscxFile", yourObject);
}

If you name your control RenderMenu.ascx, you can just do

RenderMenu()
{
    **do your work to get the data here and preferrably strong type it**
    return PartialView(yourObject);
}

Or, maybe it would make more sense to name it Menu.ascx and have a method Menu like this

Menu()
{
    **do your work to get the data here and preferrably strong type it**
    Menu myMenuObject = Repository.GetMenu(...);
    return PartialView(myMenuObject);
}

Your Menu.ascx start would look like this

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<mynamespace.Menu>" %>

To use it in a View you do it like this:

<% Html.RenderAction("Menu", "Menu"); %>

HTH

mare