Reuse your old ASP.NET Web Forms controls in Sitecore MVC

Image 15

Recently I wanted to use a control which was made for a classic ASP.NET Web Forms application with the good old sublayouts – I’m an old dog and I miss working with the ascx user controls.

So I started typing Register in the top of the razor view and… I felt really dumb here 🙂

Razor does not support web controls, instead you should use partial views or child actions

So that’s it? No way guys, you can use webcontrols in MVC. There are two ways (that I know of):

Register your webcontrol in webconfig and all is well

        <add tagprefix="mycontrol" namespace="Sandbox.Framework.Controls.PageEditor" assembly="Sandbox.Framework.Controls" />

Create an HtmlHelper extension method which will render the output from the webcontrol

I chose the latter and created an HtmlHelper extension method which will accept a webcontrol instance. In this case Sitecore.Web.UI.WebControls.FieldControl.

public static HtmlString MvcFieldControl<T>(this HtmlHelper htmlHelper, T customFieldControl) where T : FieldControl
    return new HtmlString(customFieldControl.RenderAsText());

Here is an example how to use the method in the view. The webcontrol is from one of my earlier posts Make your own Droplink control for the Sitecore Page Editor

@if (Html.IsEditMode())
  @Html.MvcFieldControl(new PageEditorDropLinkControl()
      DataSource = Html.Sitecore().CurrentRendering.DataSource,
      Field = Sandbox.Newsletter.Constants.Fields.RegistrationForm.ColumnSelectorDropdown,
      EmptyText = "No column",
      DropLinkItemTextField = Sandbox.Design.Constants.Fields.DesignColumn.ColumnValueFriendly,
      DropLinkItemTemplate = Sandbox.Design.Constants.Templates.DesignColumn,
      DropLinkItems = Sandbox.Design.Model.Repositories.PageColumnRepository.PageColumnsSettingsItem().GetChildren()

That’s all for now folks 🙂

3 thoughts on “Reuse your old ASP.NET Web Forms controls in Sitecore MVC

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.