ASP.NET MVC2 - 是否可以从部分视图访问父视图的模型数据?

发布于 2024-09-24 16:25:30 字数 228 浏览 0 评论 0原文

在处理 1--->0...1 关系时,我尝试对 0...1 端使用单独的部分视图。为了提高效率,我想使用 RenderPartial() 而不是 RenderAction()。

是否可以从该部分视图访问包含视图的模型数据,以便访问主对象的 PK/ID?

这是否只是一次可悲的黑客尝试,根本就不应该考虑?

有谁有更好的例子来说明如何使用 MVC 处理这个 1--->0...1 关系?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁把谁当真 2024-10-01 16:25:30

有点像。

如果您不将模型传递给 RenderPartial,则默认情况下会传递父视图。因此,您可以通过部分的 Model 属性来访问它。

但如果你确实传递了一个模型,那么不,部分模型看不到父模型,因为它看到的是自己的模型。

这是否只是一次可悲的黑客尝试,根本不应该考虑?

我会说“kludge”而不是“hack”,但是是的,可能是这样。 :)

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

梦里南柯 2024-10-01 16:25:30

首先问为什么需要PK?

但是,如果我确实需要的话,我会在子模型中拥有 ParentID 属性。然后你只需在发送之前设置它即可。

foreach(var vChild in Model.Children)
{
    vChild.ParentID = Model.ID;
    Html.RenderPartial(ViewName, vChild)
}

如果您需要父级的所有数据,那么您可以使用父属性并设置整个属性。

这种逻辑更适合在模型本身中,但是像这样:

List<Children> mChildren;
public void AddChild(Child tChild)
{
     tChild.ParentID = this.ID;
     mChildren.Add(tChild);
}

或类似的东西。这实际上取决于事情的设置方式,但这是总体思路。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文