简体   繁体   中英

Asp.Net Core MVC EF Model with List of Entities Create in SingleView

Hello I have following Models in ASP.NET Core 3.1 with Entity Framework using MVC Pattern:

public class Parent
{
   int ParentId {get; set;}
   
   string name {get; set;}
   
   ICollection<Child> childs {get; set;}
}
 
public class Child
{
   int ChildId {get; set;}

   string name{get;set;}
}

I would like to have CRUD Views for the Parent Class, where I can add and remove Childs dynamically and then send it to controller via submit and map Parent and Child to DBContext. Like in a Shopping Cart, where you can add items. Is a partial View for child that gets called with Ajax the best approach for this? Any advice would be very appreciated. Such more complex tasks are hard for a beginner like myself.

a partial View for child that gets called with Ajax is a good idea.With partial view,you can reuse it.And with ajax you can only need to pass a single child to controller,and don't need to refresh the page like form submit.

I think maybe you can change Child like this:

public class Child
{
   int ParentId {get; set;}

   int ChildId {get; set;}

   string name{get;set;}
}

And do like this to add partial view:

@await Html.PartialAsync("_Partial", @Model.Childs)

And then you can add child in the partial view with ajax,when button click to pass new child Content to controller.You need to pass ParentId so that you can add the Child to Childs of Parent Model.

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