MVC Framework – Encapsulating for Re-use


ASP.NET webforms offers a number of different options for re-use including extending existing controls, composite controls, custom controls and user controls. While the ASP.NET MVC framework doesn't support server controls (this isn't strictly true - it does support a very limited set of server controls), it is possible to encapsulate functionality in the form of an MVC user control.

MVC1

MVC user controls derive from System.Web.Mvc.ViewUserControl (as opposed to System.Web.UI.UserControl) and can be strongly typed in the same manner as ViewPages - ie I can have ViewUserControl<int> or more likely ViewUserControl<MyViewDataType> and I then get strongly typed access to the controlData via the ViewData property on my control (just like ViewPage).

Imagine I had a need to take some data and display it in various places in my application but always in upper case and with a red border (?). I might want to encapsulate this in a user control. In my Views/Shared folder I've added a new MVC View User Control derived from System.Web.Mvc.ViewUserControl<string> and in the markup I have:

<span style="border:solid 1px red;">
<%= ViewData.ToUpper() %>
</span>

On the page(s) where I want to use the control I simply call RenderUserControl() on my ViewPage:

<%= this.RenderUserControl("~/Views/Shared/ViewUserControl1.ascx", "The quick brown fox...") %>

This will cause an instance of the user control to be created and rendered thus giving me a piece of self-contained functionality I can re-use across my app.

Technorati Tags: ,
Skip to main content