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 ;)
-
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 }); %> -
Not the most beautiful solution
<% ViewData["imageSize"] = 100; %> <% Html.RenderPartial("_ProductImage"); %>the ViewData is passed by default
-
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
RenderPartialto give us the same functionality. Just an additionalobject dataparameter 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
PartialControlModelif 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.ImagesYou can get the data and cast it to the correct type with :
ViewData.Model.DataIf anyone has a suggestion on how to improve the generics I'm using please let me know.
-
Fabulous! Exactly what I was looking for. Thanks for all the code.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.