views:

432

answers:

4

I have a strongly typed user control ("partial") and I'd like to be able to pass it some additional information from its containing view. For example, I have view that's bound to a product class and i have a partial that also is strongly typed to that same model, but I also need to pass an additional parameter for imageSize to my partial. I'd like to be able to do something like this:

<% Html.RenderPartial("_ProductImage", ViewData.Model, new { imageSize = 100 }); %>

As far as I know there is no way to do this, but I'm hoping that someone smarter than me may have a solution ;)

+5  A: 

Change the type of the partial model:

class PartialModel 
{
    public int ImageSize { get; set; }
    public ParentModelType ParentModel { get; set; }
}

Now pass it:

<% Html.RenderPartial("_ProductImage", 
    new PartialModel() { ImageSize = 100, ParentModel = ViewData.Model }); %>
Craig Stuntz
+1  A: 

Not the most beautiful solution

<% ViewData["imageSize"] = 100; %>

<% Html.RenderPartial("_ProductImage"); %>

the ViewData is passed by default

Todd Smith
+1  A: 

I use a generic class model - which is similar in concept to the approach suggested by Craig.

I kind of wish MS would create an overload to RenderPartial to give us the same functionality. Just an additional object data parameter would be fine.

Anyway, my approach is to create a PartialModel which uses generics so it can be used for all .ascx controls.

 public class PartialControlModel<T> : ModelBase 
    {
        public T ParentModel { get; set; }
        public object Data { get; set; }

        public PartialControlModel(T parentModel, object data) : base()
        {
            ParentModel = parentModel;
            Data = data;
        }
    }

The .ascx control should inherit from the correct PartialControlModel if you want the view to be strongly typed, which most likely you do if you've got this far.

public partial class ThumbnailPanel : 
                     ViewUserControl<PartialControlModel<GalleryModel>>

Then you render it like this :

<% Html.RenderPartial("ThumbnailPanel", 
new PartialControlModel<GalleryModel>(ViewData.Model, tag)); %>

Of course when you refer to any parent model items you must use this syntax :

ViewData.Model.ParentModel.Images

You can get the data and cast it to the correct type with :

ViewData.Model.Data

If anyone has a suggestion on how to improve the generics I'm using please let me know.

Simon_Weaver
A: 

Fabulous! Exactly what I was looking for. Thanks for all the code.