MVC5 Html.RenderAction with different controller
Asked Answered
O

2

29

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?

Outroar answered 4/11, 2013 at 15:56 Comment(0)
F
59

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

Try:

@{Html.RenderAction("PriceRange", "Movies");}
Faustinafaustine answered 4/11, 2013 at 21:34 Comment(2)
@Html.Action does this without the curly braces.Savoy
@Html.Action does without braces but most of the time you need RenderAction due to better performance.Vaules
H
1

The controller name needs to be "Movies" and not "MoviesController". Because now I believe it is looking for a controller called "MoviesControllerController".

Hermetic answered 11/10, 2016 at 17:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.