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?
Partial Views can use the Page Model for their data whereas Child Actions use independent data from the Controller. Editor/Display templates pass items from the model to the system but can be overridden by user partial views.
To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.
It does not require to have a controller action method to call it. Partial view data is dependent of parent model. Caching is not possible as it is tightly bound with parent view (controller action method) and parent's model.
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. :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With