qinking126
qinking126

Reputation: 11875

asp.net mvc3, how to implement the sidebar section correctly?

I build my web site using asp.net mvc3, layout is 2 columns, main content with sidebar.

I create a section for sidebar. this sidebar will show top 10 articles. what I did right now is to query the top 10 articles on every controller.

is there a way to do it in one place and using it on all controllers?

Upvotes: 1

Views: 3304

Answers (1)

John H
John H

Reputation: 14655

You can do this using Html.RenderAction([methodname], [controllername]). So in your _Layout.cshtml, you might end up with something like:

<div id="content">
    @RenderBody()
</div>

@{ Html.RenderAction("ShowTopArticles", "Article"); }

Then in your ArticleController:

private readonly int MaxArticles = 10;

[ChildActionOnly]
public PartialViewResult ShowTopArticles()
{
    var model = articleRepository.GetTopArticles(MaxArticles);

    return PartialView(model);
}

Marking the action with the attribute ChildActionOnly means it can only be invoked by a call to Html.Action() or Html.RenderAction().

Upvotes: 6

Related Questions