Zeb Rawnsley
Zeb Rawnsley

Reputation: 2220

Render partial view from controller

I have a controller ItemsController that has an instance method GetRecent() which returns IQueryable<Item>

In the index page of my application I want to render a partial view _Recent.cshtml using the results from ItemsController.GetRecent()

To do this, I've written the following in my Index.cshtml

I've added namespace references to the ~/Views/web.config so I don't need to write out the controllers full namespace

    @{
        ViewBag.ItemsController = new ItemsController();
    }

    ...

    @Html.Partial("~/Views/Items/_Recent.cshtml",
                   ((ItemsController)ViewBag.ItemsController).GetRecentItems())

I thought of passing new ItemsController().GetRecentItems() directly or turning GetRecentItems() into a static method however I'm not sure what direction this should take.

I want to know if this is an accepted way of building a partial view from a controller and if not, how can this be accomplished more efficiently?

Upvotes: 1

Views: 3824

Answers (1)

Tim M.
Tim M.

Reputation: 54359

RenderAction

The first option is Html.Action or Html.RenderAction(What's the difference?). These are part of the ASP.Net MVC framework, and provide a more polished means to implement something similar to your code sample.

With this approach, your view calls the appropriate controller, which fetches any needed data, renders the partial view, and returns it.

I tend to shy away from using this approach as it seems backwards, i.e. the view "knows" quite a bit about controllers and controller structure and is actively executing rather than just consuming.

Still, it's a legitimate option.

Remodeling

You could pass the "recent items" along with the view model for the main view. This is more effort to model, but "pure" in that your view is less coupled to the controllers. Your partial view would not need to change.

Async Rendering

You could render the recent items using an AJAX call to the appropriate controller, and have that controller return the partial view as its result. This is probably the most effort, but elegant in that some of the work is delayed until the rest of the page is rendered (possibly allowing lazy loading, and/or improved page load times).

Done correctly, this approach also allows decent separation of concerns.


  • Related Question (not identical, as it doesn't focus on passing data to the partial view)

Upvotes: 2

Related Questions