ASP.NET MVC : Good Replacement for User Control?

Posted by David Lively on Stack Overflow See other posts from Stack Overflow or by David Lively
Published on 2010-05-10T16:55:43Z Indexed on 2010/05/25 17:01 UTC
Read the original article Hit count: 263

Filed under:
|

I found user controls to be incredibly useful when working with ASP.NET webforms. By encapsulating the code required for displaying a control with the markup, creation of reusable components was very straightforward and very, very useful.

While MVC provides convenient separation of concerns, this seems to break encapsulation (ie, you can add a control without adding or using its supporting code, leading to runtime errors). Having to modify a controller every time I add a control to a view seems to me to integrate concerns, not separate them. I'd rather break the purist MVC ideology than give up the benefits of reusable, packaged controls.

I need to be able to include components similar to webforms user controls throughout a site, but not for the entire site, and not at a level that belongs in a master page. These components should have their own code not just markup (to interact with the business layer), and it would be great if the page controller didn't need to know about the control. Since MVC user controls don't have codebehind, I can't see a good way to do this.

Update FINALLY, a good (and, in retrospect, obvious) way to accomplish this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace K.ObjectModel.Controls
{
    public class TestControl : ViewUserControl
    {
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            writer.Write("Hello World");
            base.Render(writer);
        }
    }
}

Create a new class which inherits ViewUserControl

Override the .Render() method as shown above.

Register the control via its associated ASCX as you would in a webForm:

<%@ Register TagName="tn" TagPrefix="k" Src="~/Views/Navigation/LeftBar.ascx"%>

Use the corresponding tag in whatever view or master page that you need:

<k:tn runat="server"/>

Make sure your .ascx inherits your new control:

<%@ Control Language="C#" Inherits="K.ObjectModel.Controls.TestControl" %>

Voila, you're up and running. This is tested with ASP.NET MVC 2, VS 2010 and .NET 4.0.

Your custom tag references the ascx partial view, which inherits from the TestControl class. The control then overrides the Render() method, which is called to render the view, giving you complete control over the process from tag to output.

Why does everyone try to make this so much harder than it has to be?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about usercontrols