简体   繁体   中英

Access parent model data from child in ASP.NET MVC

I am building small web application with ASP.NET MVC C#. 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:

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

When clicked, we go to ChildIndexView and list of all Children under Parent model. 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. How can I retrieve that ParentId and pass it to 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. If it is not null, I take FirstOrDefault object from model and pass ParentId to a 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. How can I send ParentId to a Child element from this position?

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> . You have two options:

Define a new viewmodel which contains the list of Child and the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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