title: Access parent model data from child in ASP.NET MVC
body: <p>I am building small web application with ASP.NET MVC C#. I have two models:</p>
  
  <pre><code>public class Parent
  {
      public Guid Id { get; set; }
  
      public virtual ICollection&lt;Child&gt; Children { get; set; }
  }
  public class Child
  {
      public Guid Id { get; set; }
  
      public Guid ParentId{ get; set; }
      public virtual Parent Parent { get; set; }
  }
  </code></pre>
  
  <p>And I have ParentView where I send Parent Id to Child Controller with ActionLink, like this:</p>
  
  <pre><code>@Html.ActionLink("something", "ChildIndexMethod", "ChildController", new { parentId=item.Id}, null)
  </code></pre>
  
  <p>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? </p>
  
  <p>I did this:</p>
  
  <pre><code>if (Model.FirstOrDefault() != null) 
      { 
          @Html.ActionLink("New child", "NewChild", new { parentId = Model.FirstOrDefault().ParentId})
      }
      else
      {
          //What to do if Model is null?
      }
  </code></pre>
  
  <p>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?</p>
  
  <p>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.</p>
  
  <p>Thank you</p>