0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.