【问题标题】:Access parent model data from child in ASP.NET MVC在 ASP.NET MVC 中从子访问父模型数据
【发布时间】:2016-05-01 01:10:34
【问题描述】:

我正在使用 ASP.NET MVC C# 构建小型 Web 应用程序。我有两个模型:

public class Parent
{
    public Guid Id { get; set; }

    public virtual ICollection<Child> Children { get; set; }
}
public class Child
{
    public Guid Id { get; set; }

    public Guid ParentId{ get; set; }
    public virtual Parent Parent { get; set; }
}

我有 ParentView,我使用 ActionLink 将 Parent Id 发送到 Child Controller,如下所示:

@Html.ActionLink("something", "ChildIndexMethod", "ChildController", new { parentId=item.Id}, null)

点击后,我们转到 ChildIndexView 和 Parent 模型下的所有 Child 的列表。从那里,我想要的是能够在同一个父母下创建新的孩子。要创建新的 Child,我需要将 ParentId 提供给新的 Child 对象。如何检索该 ParentId 并将其传递给 Child?

我这样做了:

if (Model.FirstOrDefault() != null) 
    { 
        @Html.ActionLink("New child", "NewChild", new { parentId = Model.FirstOrDefault().ParentId})
    }
    else
    {
        //What to do if Model is null?
    }

首先我检查模型是否不为空。如果它不为空,我会从模型中获取 FirstOrDefault 对象并将 ParentId 传递给 Child。但它只有在父级下已经有子级时才有效。如果 Parent 下没有 Children,我无法读取 ParentId,因此会发生错误。如何从这个位置将 ParentId 发送到子元素?

我知道这可能是实现我目标的错误方法。但我还在学习。此外,我无法在 SO 上找到答案。任何帮助表示赞赏。

谢谢

【问题讨论】:

    标签: c# asp.net-mvc entity-framework parent


    【解决方案1】:

    似乎子视图中的模型是IEnumerable&lt;Child&gt;。你有两个选择:

    定义一个包含 Child 列表和 parentid 的新视图模型:

    public ChildListViewModel
    {
        public Guid ParentId {...}
        public IEnumerable <Child> Children {...}
    }
    

    使用查看包

    ViewBag.ParentId = parentId;
    

    即使您没有任何 Child,两者都会在您的视图中显示 ParentId

    【讨论】:

    • 儿童视图中的模型是PagedList,但是您的两种方法都在现场。谢谢
    • 因此,您可以在 IEnumerable 上使用 PagedList。问候
    猜你喜欢
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多