Integrate Action Methods into ASP.NET MVC Partial Views
I find it handy to assemble complex Views from multiple simpler Partial Views. Sometimes, however, the result is a lot of code in my Views (I even did a column about managing that code). But there's another solution: The HtmlHelper's Action helper method, which allows you to call an action method and incorporate the results of that action method into your View.
This code in a View, for example, calls an action method named DisplayCustomer and adds the Partial View returned by DisplayCustomer to the View:
@Html.Action("DisplayCustomer")
My example is just the simplest way to call your action method -- you can also pass a controller name and an anonymous object with various property values.
Using the Action method lets you put much of your View-related logic where it belongs: in a method in your controller and not in your View (in the MVC design pattern, Views should have no logic at all). And, of course, once your logic is in a controller method, you can test it.
You probably don't want anyone invoking one of these action methods directly. You can tell ASP.NET MVC not to let that happen by decorating your action method with the ChildActionOnly attribute, like this:
<ChildActionOnly>
Function DisplayCustomer() As ActionResult
Return PartialView("CustomerData")
End Function
Posted by Peter Vogel on 09/04/2015