R – What’s the best way to implement user controls in ASP.NET MVC

asp.net-mvcuser-controls

Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff.

I'm wondering about how user controls work in ASP.NET MVC. We have tons of .ASCX controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer.

What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration.

Best Answer

To implement a user control you do the following call:

<% Html.RenderPartial("~/Views/Shared/MyControl.ascx", {data model object}) %>

You may also see the older syntax which as of PR5 is not valid anymore

<%= Html.RenderUserControl("~/Views/Shared/MyControl.ascx", {data model object}) %>

You will always have to worry about code breaking when moving from Web Forms to MVC, however the ASP.NET MVC team has done a great job to minimize the problems.