MVC5 Html.RenderAction with different controller

SamTech picture SamTech · Nov 4, 2013 · Viewed 73.7k times · Source

I am starting with MVC5 and created first project from MVC5 Getting Started.

Now trying with Partial Rendering and added a method in MoviesController as below

[ChildActionOnly]
public ActionResult PriceRange()
{
   var maxprice = db.Movies.Max(m => m.Price);
   var minprice = db.Movies.Min(m => m.Price);
   ViewBag.MaxPrice = maxprice;
   ViewBag.MinPrice = minprice;
   return PartialView();
}

It sets Min and Max price from Movies collection into ViewBag that are later displayed at view. I am trying to render it on different views.

First i tried to render it at Views/Movies/Index.cshtml as below

@{Html.RenderAction("PriceRange");}

It works well there and results displayed correctly because it is using MoviesController, the same class where method PriceRange defined.

Then i tried to render it at Views/Hello/Index.cshtml (this view is using HelloWorldController) with following code (first passing Action name then Controller name)

@{Html.RenderAction("PriceRange", "MoviesController");}

Here it is giving run-time error

The controller for path '/HelloWorld/Index' was not found or does not implement IController.

Here is complete code from Views/Hello/Index.cshtml

@{
    ViewBag.Title = "Movie List";
}
<h2>My Movie List</h2>
<p>Hello from our view template</p>
@{Html.RenderAction("PriceRange", "MoviesController");}

I found few examples through Google, they are calling RenderAction helper the same way, first passing Action name then Controller name.

I couldn't understand what the wrong i am doing here. Can someone point out?

Answer

Charlino picture Charlino · Nov 4, 2013

It might be that you're adding the "Controller" postfix to the controller name which isn't required.

Try:

@{Html.RenderAction("PriceRange", "Movies");}