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
<configuration> <system.web> <pages> <controls> <add tagprefix="mycontrol" namespace="Sandbox.Framework.Controls.PageEditor" assembly="Sandbox.Framework.Controls" /> </controls> </pages> </system.web> </configuration>
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 🙂
Nice! And a 3rd option: sitecore renderings: http://www.chrisvandesteeg.nl/2014/02/11/usercontrol-renderings-in-a-sitecore-mvc-website-wffm-for-mvc/
LikeLiked by 1 person
Thanks 🙂 Wow! Great post with the usercontrol renderings, how could I have missed that one.
LikeLike
Nice! And a 3rd option is to mix in sitecore renderings : http://www.chrisvandesteeg.nl/2014/02/11/usercontrol-renderings-in-a-sitecore-mvc-website-wffm-for-mvc/
LikeLike