Create controller for partial view in ASP.NET MVC

brenjt picture brenjt · Jun 9, 2011 · Viewed 103.7k times · Source

How can I create an individual controller and model for a partial view? I want to be able to place this partial view any where on the site so it needs it's own controller. I am current rendering the partial as so

@Html.Partial("_Testimonials")

Answer

George Stocker picture George Stocker · Jun 9, 2011

Why not use Html.RenderAction()?

Then you could put the following into any controller (even creating a new controller for it):

[ChildActionOnly]
public ActionResult MyActionThatGeneratesAPartial(string parameter1)
{
    var model = repository.GetThingByParameter(parameter1);
    var partialViewModel = new PartialViewModel(model);
    return PartialView(partialViewModel); 
}

Then you could create a new partial view and have your PartialViewModel be what it inherits from.

For Razor, the code block in the view would look like this:

@{ Html.RenderAction("Index", "Home"); }

For the WebFormsViewEngine, it would look like this:

<% Html.RenderAction("Index", "Home"); %>