About Action and RenderAction helper methods in MVC
Generally Action and RenderAction helper methods in MVC are used for rendering child views. But both the methods have different syntax and there are some differences between these two helper methods which we are going to see in this article.
Action and RenderAction helper methods are used to render child views.
The first difference between these two methods is: The Action method returns the child view as a string whereas The RenderAction method renders the child view in place.
For example the following method is used to render the childview:
public ActionResult ChildData()
{
return View();
}
In order To call the action method and render the child view from the parent view, we can use Action helper method or RenderAction helper method as shown below:
// Renders the output as a string
<%= Html.Action("ChildData") %>
//Renders in place
<% Html.RenderAction("ChildData"); %>
Another difference is that Html.Action uses <%= whereas Html.RenderAction uses <% to render the output. the Html.Action method uses <%= because it returns a string.
We can also pass parameters to this Helper Methods as shown below:
<% Html.RenderAction("Result", new { section = "Announcement" }); %>
Above code, calls the Result action method. In this case, it passes an anonymous object that contains values for the name of the child view to render for that section. The markup renders a "Announcement" section.
The code for the Result action method is as shown below:
public ActionResult Result(string section)
{
return View(section);
}
RenderAction() allows you to call a separate controller Action/View from your original View. With this approach you can move the business logic to a separate controller/action, and create its own View to render the output.
We can also use RenderAction method to call Action Methods of different Controller or Area than the current one as shown below:
Example 1:
<% Html.RenderAction("Result", "Section"); %>
Here the first parameter is the Action method name and the second parameter is the controller name. So it calls the Result action method of the SecionController.
Example 2: In the below example we will call the Display action method which is located in another area called "Navigation":
<% Html.RenderAction("Display", new { area = "Navigation" }); %>
Example 3: In the below example we will call the Display action method of the AccountController controller and located in another area called "Navigation":
<%Html.RenderAction("Display", "Account", new { area = "Navigation" });%>