问题描述
我这么问是因为我将创建的局部视图是空白的,与创建一个新的子实体的目的。我只是需要一个快速的,不管脏,办法从局部视图中访问父模型。我需要家长的ID。
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?
推荐答案
除非你在渲染时,它传递一定的价值这一部分作为参数不能从一个局部视图访问父模型。例如,在你的主观点:
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 }));
,然后里面的部分,你可以访问编号
:
<div>@ViewBag.Id</div>
当然,这是将数据传递到局部视图的pretty糟糕的方式。正确的方法是使用强类型的视图模型。
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.
这篇关于从局部视图访问父模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!