views:

92

answers:

2

In handling a 1--->0...1 relationship, I'm trying to use a separate partial view for the 0...1 end. I'd like to use RenderPartial() rather than RenderAction(), for the sake of efficiency.

Is it possible to gain access to the containing view's model data from this partial view, in order to access the PK/ID of the main object?

Is this just a sad attempt at a hack that shouldn't even be considered in the first place?

Does anyone have a better example of how to handle this 1--->0...1 relationship using MVC?

+1  A: 

Sort of.

If you don't pass a model to RenderPartial, the parent's view is passed by default. So you can access it via the partial's Model property.

But if you do pass a model, then no, the partial can't see the parent's model, because it sees its own instead.

Is this just a sad attempt at a hack that shouldn't even be considered in the first place?

I'd say "kludge" rather than "hack", but yes, probably. :)

Craig Stuntz
Hmm...it's complaining about having the wrong type passed to it...
PolishedTurd
It will have the "wrong" type if (1) the partial is strongly typed and (2) the parent and the partial require different types.
Craig Stuntz
Indeed. I'm trying to retain the separation, for binding/validation purposes, and think I may have to pursue a different sort of "kludge" in this scenario. Probably wind up tacking on the ParentObjectID as a property on the ChildObject. Ick.
PolishedTurd
+1  A: 

First ask why you need the PK?

However I'd have a ParentID property in the child model if I really needed to have it. Then you just set it before you send it off.

foreach(var vChild in Model.Children)
{
    vChild.ParentID = Model.ID;
    Html.RenderPartial(ViewName, vChild)
}

If you needed ALL of the data from the parent then you can have a Parent Property instead and set the whole property.

This logic would be better suited to be in the Model itself however like this:

List<Children> mChildren;
public void AddChild(Child tChild)
{
     tChild.ParentID = this.ID;
     mChildren.Add(tChild);
}

or something of the sort. It would really depend on how things are set up already, but that's the general idea.

Rangoric