Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC2 - is it possible to access parent view's model data from partial view?

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?

like image 623
asfsadf Avatar asked Sep 24 '10 17:09

asfsadf


People also ask

Can we use model in partial view?

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.

How do you pass model data to partial view?

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.

Can partial view have controller?

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.


2 Answers

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. :)

like image 127
Craig Stuntz Avatar answered Nov 11 '22 20:11

Craig Stuntz


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.

like image 26
Rangoric Avatar answered Nov 11 '22 19:11

Rangoric