Reputation: 3862
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?
Upvotes: 6
Views: 4224
Reputation: 2799
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.
Upvotes: 3
Reputation: 126547
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. :)
Upvotes: 4