Click here to Skip to main content
16,016,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Having problems getting this ASP.NET Core MVC 3.1 web app to save form values to a SQL DB. Clicking the form's submit button does not throw an error or store the values to the DB; it just returns to Index. Any help much appreciated.



// DB CONTEXT
C#
namespace AuthSystem.Models
{
    public class G2PDataCollectionContext : DbContext
    {
        public G2PDataCollectionContext(DbContextOptions<G2PDataCollectionContext> options) : base(options)
        {
        }
        public DbSet<G2P_DataCollection> G2P_DataCollections { get; set; }
        public DbSet<G2P_DataCollection_Detail> G2P_DataCollections_Details { get; set; }
    }
}

// MODEL
C#
namespace AuthSystem.Models
{
    public class G2P_DataCollection_Detail
    {        
        [Key]
        public int Id { get; set; }
        [Required]
        public int G2P_DC_Id { get; set; }
        [Required]
        [Display(Name = "Genotype Number")]
        public int GenotypeNumber { get; set; }
        [Required]
        [Display(Name = "Seedling Replicate Number")]
        public int SeedlingReplicateNumber { get; set; }
        [Required]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [DataType(DataType.Date)]
        [Display(Name = "Germination Date")]
        public DateTime GerminationDate { get; set; }
        [Required]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [DataType(DataType.Date)]
        [Display(Name = "Phenotyping Date")]
        public DateTime PhenotypingDate { get; set; }
        [Required]
        [Display(Name = "Manual2LA")]
        public decimal Manual2LA { get; set; }
        [Required]
        [Display(Name = "Manual3LA")]
        public decimal Manual3LA { get; set; }
        [Required]
        [Display(Name = "Digital2LA")]
        public decimal Digital2LA { get; set; }
        [Required]
        [Display(Name = "Digital3LA")]
        public decimal Digital3LA { get; set; }        
        [Display(Name = "Notes")]
        public string Notes { get; set; }
        public DateTime TimeStamp { get; set; }
    }
}

// VIEW
C#
@using AuthSystem.Areas.Identity.Data
@model List<AuthSystem.Models.G2P_DataCollection_Detail>
@{
    ViewData["Title"] = "Create Detail";
    Layout = "~/Views/Shared/_Layout_g2p_DC_Details.cshtml";
}
<div style="overflow-x:auto;">
    <table id="tblCustomers" cellpadding="0" cellspacing="0">
        <thead>
            <tr>
                <th>Row#</th>
                <th>Genotype#</th>
                <th>SeedReplicate#</th>
                <th>GerminationDate</th>
                <th>PhenotypingDate</th>
                <th>Manual2LA</th>
                <th>Manual3LA</th>
                <th>Digital2LA</th>
                <th>Digital3LA</th>
                <th>Notes</th>
            </tr>
        </thead>
        <tbody>           
            <form asp-controller="G2P_DataCollection" asp-action="CreateDetailPost" method="post">
                @for (var i = 1; i < Model.Count(); i++)
                {
               <tr>
                  <td>@i</td>
                  <td><input asp-for="@Model[i].GenotypeNumber" class="form-control form-control-sm" /></td>
                  <td><input asp-for="@Model[i].SeedlingReplicateNumber" class="form-control form-control-sm" /></td>
                  <td><input asp-for="@Model[i].GerminationDate" class="form-control form-control-sm" /></td>
                  <td><input asp-for="@Model[i].PhenotypingDate" class="form-control form-control-sm" /></td>
                  <td><input asp-for="@Model[i].Manual2LA" class="form-control form-control-sm" /></td>
                  <td><input asp-for="@Model[i].Manual3LA" class="form-control form-control-sm" /></td>
                  <td><input asp-for="@Model[i].Digital2LA" class="form-control form-control-sm" /></td>
                  <td><input asp-for="@Model[i].Digital3LA" class="form-control form-control-sm" /></td>
                  <td><textarea asp-for="@Model[i].Notes" class="form-control form-control-sm"></textarea></td>            
               </tr>                 
                }
            <input type="submit" value="Submit all" class="btn btn-primary" />
            </form>
        </tbody>
        <tfooter>
        </tfooter>
    </table>
</div>

// CONTROLLER
C#
namespace AuthSystem.Controllers
{
    [Authorize(Roles = "Admin, Teacher, Student")]
    public class G2P_DataCollectionController : Controller
    {
        private readonly G2PDataCollectionContext _context;
        private readonly AuthDBContext _authContext;
        private readonly AREsContext _areContext;
        private readonly UserManager<ApplicationUser> userManager;
        private readonly IEmailSender _emailSender;
        private readonly IWebHostEnvironment env;
        public G2P_DataCollectionController(G2PDataCollectionContext context, AuthDBContext authContext, AREsContext areContext, UserManager<ApplicationUser> usrMgr, IEmailSender emailSender, IWebHostEnvironment env)
        {
            _context = context;
            _authContext = authContext;
            _areContext = areContext;
            userManager = usrMgr;
            _emailSender = emailSender;
            this.env = env;
        }
// GET: G2P_DataCollection/CreateDetail
public IActionResult CreateDetail()
{
   var dcId = Convert.ToInt32(TempData["Id"]); // Id of DataCollection master record
   var myModels = new List<G2P_DataCollection_Detail>();
   for (var i = -1; i < dcId; i++) // dynamically build input form using Model and #plants value.
   {
      myModels.Add(new G2P_DataCollection_Detail());
   }
   return View(myModels);
// POST: G2P_DataCollection/CreateDetailPost      
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateDetailPost(List<G2P_DataCollection_Detail> G2P_DataCollections_Details)
   {
      if (ModelState.IsValid)
      {
         foreach (var myModel in G2P_DataCollections_Details)
         {
            _context.G2P_DataCollections_Details.Add(myModel);
         }
         _context.SaveChanges();
         return RedirectToAction("Index");
      }
      return View(G2P_DataCollections_Details);

// DB TABLE
SQL
CREATE TABLE [dbo].[G2P_DataCollections_Details](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[G2P_DC_Id] [int] NULL,
	[GenotypeNumber] [int] NULL,
	[SeedlingReplicateNumber] [int] NULL,
	[GerminationDate] [date] NULL,
	[PhenotypingDate] [date] NULL,
	[Manual2LA] [decimal](18, 2) NULL,
	[Manual3LA] [decimal](18, 2) NULL,
	[Digital2LA] [decimal](18, 2) NULL,
	[Digital3LA] [decimal](18, 2) NULL,
	[Notes] [nvarchar](max) NULL,
	[TimeStamp] [datetime2](7) NULL,
 CONSTRAINT [PK_G2P_DataCollections_Detail] PRIMARY KEY CLUSTERED


What I have tried:

Scoured internet and am stuck after days of trial and error to get to this point...
Posted
Updated 2-Oct-22 22:28pm
v3
Comments
OriginalGriff 1-Oct-22 23:31pm    
Please don't double space your code: it makes it harder to read as less fits on a screen and it has to be scrolled into view. It doesn't make it look "bigger" or "better", it just makes it look less impressive and harder to work with.
And in future, please use the "code" button on the toolbar to add formatting to your code - it makes it a lot more readable!
I've updated your question to fix both, but you should probably check it to see what I did and if it accurately reflects your code structure.
Andrew Helbling 2-Oct-22 14:56pm    
Thank you.
OriginalGriff 2-Oct-22 15:57pm    
You're welcome!

1 solution

Quote:
Razor
@for (var i = 1; i < Model.Count(); i++)
Your loop always skips the first item in the list. As a result, the model binder will not be able to bind the submitted data to a List<T>.

You need to change the loop to start at 0 instead of 1.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900