简体   繁体   English

从ASP.NET MVC中的子级访问父级模型数据

[英]Access parent model data from child in ASP.NET MVC

I am building small web application with ASP.NET MVC C#. 我正在使用ASP.NET MVC C#构建小型Web应用程序。 I have two models: 我有两个模型:

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; }
}

And I have ParentView where I send Parent Id to Child Controller with ActionLink, like this: 而且我有ParentView,其中我通过ActionLink将父ID发送给子控制器,如下所示:

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

When clicked, we go to ChildIndexView and list of all Children under Parent model. 单击后,我们转到ChildIndexView并在“父”模型下列出所有子级。 From there, what I want is to be able to create new Child under same Parent. 从那里,我想要的是能够在同一个父项下创建新的子级。 To create new Child I need to provide ParentId to a new Child object. 要创建新的Child,我需要为新的Child对象提供ParentId。 How can I retrieve that ParentId and pass it to Child? 如何检索该ParentId并将其传递给Child?

I did this: 我这样做:

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

First I check if Model is not null. 首先,我检查Model是否不为null。 If it is not null, I take FirstOrDefault object from model and pass ParentId to a Child. 如果不为null,则从模型中获取FirstOrDefault对象,然后将ParentId传递给Child。 But it only works if there are Children already under Parent. 但是,只有在“父母”下已经有孩子的情况下,此方法才有效。 IF there are no Children under Parent, I cannot read ParentId and thus error occurs. 如果在父项下没有子项,则无法读取ParentId,因此会发生错误。 How can I send ParentId to a Child element from this position? 如何从该位置将ParentId发送给Child元素?

I know this is probably wrong method to achieve my goal. 我知道这可能是实现目标的错误方法。 But I am still learning. 但是我还在学习。 Also, I was not able to find answer on SO. 另外,我也无法找到答案。 Any help is appreciated. 任何帮助表示赞赏。

Thank you 谢谢

It seems the Model in the children view is an IEnumerable<Child> . 子视图中的Model似乎是IEnumerable<Child> You have two options: 您有两种选择:

Define a new viewmodel which contains the list of Child and the parentid: 定义一个新的viewmodel,其中包含Child和parentid的列表:

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

Use view bag 使用查看包

ViewBag.ParentId = parentId;

Both will make ParentId available in your view even if you don't have any Child 即使您没有任何孩子,两者都会在您的视图中使ParentId可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM