views:

1332

answers:

3

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 lifecycle, 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.

+8  A: 

To impliment 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 WebForms to MVC, however the ASP.NET MVC team has done a great job to minimize the problems.

Nick Berardi
+1  A: 

As Nick suggested, you will indeed be able to render your user controls, but obviously the page-cycle, pagestate and postback from traditional ASP Webforms won't work anymore, thus making your controls most likely useless.

I think you'll have to rewrite most of your complex controls to port your website to MVC, while simple controls which, for instance, provide only formatting and have no postback status, should simply work. The code provided by Nick will simply work in this case.

And about sharing between more projects: I think controls will be more like "reusable HTML-rendering components" that can be shared across a website, rather than "reusable code components" with logic (like WebForms controls). Your web logic will/should be in the pages controllers and not in the HTML controls. Therefore sharing controls across more projects won't be so useful as in the WebForms case.

Lck
+1  A: 

Yeah, you can do RenderPartial. That's a good start. But eventually these guys will need logic and other controllery type stuff. Be on the lookout for a subcontroller implementation from the framework team. There should also be something in MvcContrib soon. Or roll your own.

Edit: I just posted about this here: http://mhinze.com/subcontrollers-in-aspnet-mvc/

Matt Hinze