0
I’m building a master details page that is multiple details records with single master record. but only one detail record is being saved into the data base. I tried to debug & found that detail loop is getting value only once even though the csthml page has dynamic input controls . Here is my Code for save method:
using Microsoft.AspNetCore.Mvc;
using TestApplication_timesheet.Data;
using TestApplication_timesheet.Models;
namespace TestApplication_timesheet.Controllers
{
public class TimeSheetController : Controller
{
private readonly ApplicationDbContext _context;
public TimeSheetController(ApplicationDbContext context )
{
_context = context;
}
public IActionResult Index()
{
List<TimeSheetHeader> timeSheetHeader = _context.TimeSheetHeader.ToList();
return View(timeSheetHeader);
}
public IActionResult Create()
{
TimeSheetHeader timeSheetHeader=new TimeSheetHeader();
timeSheetHeader.TimeSheetDetails.Add(new TimeSheetDetails() { Id = 1 });
return View("Create", timeSheetHeader);
}
[HttpPost]
public IActionResult Create(TimeSheetHeader timesheetheader)
{
_context.TimeSheetHeader.Add(timesheetheader);
// Iterate through TimeSheetDetails and save each explicitly
foreach (var detail in timesheetheader.TimeSheetDetails)
{
_context.TimeSheetDetails.Add(detail); // Ensure TimeSheetHeaderId is set
}
_context.SaveChanges();
return RedirectToAction("Index");
}
}
}
Expecting the mutiple detail lines are saved to the db. the create action method saves only one line. The model class for header and details are set as below. Tried many solutions from the blogs with no luck. Any help would be appreciated
Rajesh Nambiar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.