Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Parent Model from partial view

I'm asking because the partial view I will create is blank, with the purpose of creating a new child entity. I just need a quick, regardless if dirty, way to access the Parent Model from within the partial view. I need the Id of the parent.

Does a partial view automatically have access to the model of the parent?

like image 632
AnimaSola Avatar asked Mar 10 '13 12:03

AnimaSola


2 Answers

You cannot access the parent model from a partial view unless you pass some value to this partial as parameters when rendering it. For example in your main view:

@model MyViewModel
...
@Html.Partial("_myPartial", new ViewDataDictionary(new { id = Model.Id }));

and then inside your partial you could access the Id:

<div>@ViewBag.Id</div>

Of course this is a pretty lousy way of passing data to a partial view. The correct way is to use a strongly typed view model.

like image 150
Darin Dimitrov Avatar answered Nov 02 '22 12:11

Darin Dimitrov


I know this is an old topic, but I figured I'd just add my solution to the same problem anyway. I think it's a bit cleaner.

Basically add a model to the partial view.

The encapsulating view:

@model whatever
...
@Html.Partial("partialview", anotherwhatever)

The partial view:

@model anotherwhatever
<div>@Model.something</div>
...

In my case I just needed to pass a string into the partial view (just using it to shorten and partition code), so this was much more elegant than the other solution.

I tried the other solution first and actually couldn't get it to work, it just acted as though the value I passed was blank.

like image 2
Yushatak Avatar answered Nov 02 '22 12:11

Yushatak