Reputation: 616
Suppose a Parent
model with a one-to-many relationship to several Child
models. From a details page for a Parent
, I want to link to a Child
creation form. A Child
entity created there is then supposed to belong to the Parent
.
I understand how to "work the context" in order to connect the Child
with the Parent
. My question is about getting a Parent
reference from the Parent
view to the Child
creation view.
I have found some solutions that seem very "low level" (e.g. setting the parent ID in TempData
). I assume there is a more idiomatic (maybe even type-safe) way to do this.
I am using razor templates in Areas, if that makes a difference.
Upvotes: 0
Views: 56
Reputation: 2909
Create a data-structure let's say CreateChildViewModel
public class CreateChildViewModel
{
public int ParentId {get;set;}
//... rest of the props
}
Now you can navigate to your CreateParentChild action and pass the id in the link using tag helpers <a asp-controller="YourController" asp-action="CreateParentChild" asp-route-parentId="YourParentId"></a>
[HttpGet]
public IActionResult CreateParentChild(int parentId) =>
View(new CreateChildViewModel { ParentId = parentId });
and then in your view you can store this id in a hidden input field
@model YourNamespace.CreateChildViewModel
<input type="hidden" asp-for="ParentId" />
once you post this back to create the child you will have the Id in the form.
[HttpPost]
public IActionResult CreateParentChild(CreateChildViewModel vm) {
//do your stuff
}
I'd say as a rule of thumb try to never use TempData
Upvotes: 1