CodeGarden 10: The sixth annual Umbraco Developer Conference
June 23-25th 2010 - free ASP.NET MVC pre-conference. Register today!

Minutes for MVC Usercontrols session

Participants: Morten Bock, Paul Sterling, Kim Løwert, Asbjørn Uslberg, Jesper Ordrup

We tried to figure out how to pass data from the controller to the UserControl that was placed in the View. One challenge is to get strongly typed data.

You can pass multiple objects by using ViewData["somekey"], but that will require that the usercontrol casts the data that is received + it can lead to problems when multiple usercontrols want to use the same key value.

Another solution is to pass the object using the ViewData.Model, however the problem is that you can only pass one model, so the ViewData would have to be extended to contain multiple models.

The tricky part seems to be how to figure out when to load data for the usercontrol. In theory the controller can not know wether or not a usercontrol is placed in a view. This means that you would either load data for every usercontrol, or for none of them.

One suggestion was to make it sort of event driven, so the writer of the usercontrol also needed to hook up to the controllers "init" event, in order to request the data that the view needs.

In general, it seems that the whole usercontrol concept is not very MVC friendly with regards to working on external data, so this is a subject that needs further investigation.

Update:

Upon further investigation it is possible to create a separate project containing a ViewUserControl, Controller and Model and then inserting it in an umbraco template view by using the RenderAction method from the Microsoft.Web.Mvc project:

<% Microsoft.Web.Mvc.ViewExtensions.RenderAction<MyMvcPackage.Controllers.MyController>(this.Html, x => x.MyAction()); %>