.NET Tips and Tricks

Blog archive

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


comments powered by Disqus

Featured

  • GitHub Copilot for Azure Gets Preview Glitches

    This reporter, recently accepted to preview GitHub Copilot for Azure, has thus far found the tool to be, well, glitchy.

  • New .NET 9 Templates for Blazor Hybrid, .NET MAUI

    Microsoft's fifth preview of .NET 9 nods at AI development while also introducing new templates for some of the more popular project types, including Blazor Hybrid and .NET MAUI.

  • What's Next for ASP.NET Core and Blazor

    Since its inception as an intriguing experiment in leveraging WebAssembly to enable dynamic web development with C#, Blazor has evolved into a mature, fully featured framework. Integral to the ASP.NET Core ecosystem, Blazor offers developers a unique combination of server-side rendering and rich client-side interactivity.

  • Nearest Centroid Classification for Numeric Data Using C#

    Here's a complete end-to-end demo of what Dr. James McCaffrey of Microsoft Research says is arguably the simplest possible classification technique.

  • .NET MAUI in VS Code Goes GA

    Visual Studio Code's .NET MAUI workload, which evolves the former Xamarin.Forms mobile-centric framework by adding support for creating desktop applications, has reached general availability.

Subscribe on YouTube