Thursday 2 February 2023

How to save dynamically added rows in MVC

 

How to save dynamically added rows in MVC

This article shows How to add dynamically rows on button click event and save all the data into database using asp.net mvc

Here we are performing this problem using below example with detailed description.

 

 

 

 

 

 

 

 

 

 

 

 

 

Time In

Time Out

 

 

 

 

__________

___________

Add New

 

 

 

__________

___________

Add New

 

 

 

 

 

 

 

 

 

Save

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

In

Out

Duration

Action

 

 

09:30

12:30

03:00

Delete

 

 

13:00

16:30

03:30

Delete

 

 

16:45

19:00

02:15

Delete

 

 

 

 

 

 

 

 

In Hours

Out Hours

First In

Last Out

 

 

08:45

00:45

09:30

19:00

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Here is the problem statement.

When you click on the “Add New” Button, it should generate a new row for the time entry below the existing one. Users should be able to add as many entries he/she wants to add.

Clicking on Save, all those entries should be saved in the database and should be displayed in the below grid with proper Duration, In Hours, Out Hours, First In & Last Out values.

Clicking on Delete should ask for confirmation “Are you sure you want to delete?”. If the user says Yes, that entry should be deleted and update all calculated fields.

Please find Below steps :

1. Create Database Table :

CREATE TABLE [dbo].[TimeEntryDetail](

[TimeEntryId] [int] IDENTITY(1,1) NOT NULL,

[InTime] [time](7) NOT NULL,

[OutTime] [time](7) NOT NULL,

[Duration] [time](7) NOT NULL,

2. Add  Using Database First Approach Data model in your application. 

namespace Test.Models

{

    using System;

    using System.Collections.Generic;

    using System.ComponentModel.DataAnnotations;

     public partial class TimeEntryDetail

    {

        public int TimeEntryId { get; set; }

         [Display(Name ="In")]

        public System.TimeSpan InTime { get; set; }

        [Display(Name = "Out")]

        public System.TimeSpan OutTime { get; set; }

        public System.TimeSpan Duration { get; set; }

    }

}

3. Add following code to view to add dynamic rows using jquery.

@model IEnumerable<Test.Models.TimeEntryDetail>

@using Test.Models

@{

    ViewBag.Title = "Create";

}

    <table id="tblTimeEntry" class="table" cellpadding="0" cellspacing="0">

        <thead>

            <tr>

                <th style="width:150px">Time In</th>

                <th style="width:150px">Time Out</th>

                <th></th>

            </tr>

        </thead>

        <tbody>

            @*@foreach (TimeEntryDetail timedetail in Model)

            {

                <tr>

                    <td>@timedetail.InTime</td>

                    <td>@timedetail.OutTime</td>        

                </tr>

            }*@

        </tbody>

        <tfoot>

            <tr>

                <td><input type="time" id="txtInTime" /></td>

                <td><input type="time" id="txtOutTime" /></td>

                <td><input type="button" id="btnAdd" value="Add New"  class="btn btn-primary" /></td>

            </tr>

        </tfoot>

    </table>

    <br />

    <input type="button" id="btnSave" value="Save" class="btn btn-success" />

    <br /><br />

    @Html.ActionLink("Go to Time Entries", "Detail")

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>

    <script type="text/javascript">

        function validEntry()

        {

            var In = $("#txtInTime").val();

            var Out = $("#txtOutTime").val();

            if (In == "" || Out == "") {

                alert("Please valid In and Out Entry both");

                return false;

            }

            else { return true;}

        }

        $("body").on("click", "#btnAdd", function () {

            if (validEntry() == true) {

                var txtInTime = $("#txtInTime");

                var txtOutTime = $("#txtOutTime");

                var tBody = $("#tblTimeEntry > TBODY")[0];

                var row = tBody.insertRow(-1);

                var cell = $(row.insertCell(-1));

                cell.html(txtInTime.val());

                cell = $(row.insertCell(-1));

                cell.html(txtOutTime.val());

                txtInTime.val("");

                txtOutTime.val("");

            }

        });


        $("body").on("click", "#btnSave", function () {

                var timeDetails = new Array();

                $("#tblTimeEntry TBODY TR").each(function () {

                    var row = $(this);

                    var timedetail = {};

                    timedetail.InTime = row.find("TD").eq(0).html();

                    timedetail.OutTime = row.find("TD").eq(1).html();

                    timedetail.duration = (new Date(timedetail.OutTime) - new Date(timedetail.InTime));

                    timeDetails.push(timedetail);

                });

            //Send the JSON array to Controller using AJAX.

            $.ajax({

                type: "POST",

                url: "/TimeEntry/Create",

                data: JSON.stringify(timeDetails),

                contentType: "application/json; charset=utf-8",

                dataType: "json",

                success: function (r) {

                    alert(r + " Entry(s) Added into Timesheet");

                }

            });

        });

    </script>


4. Add below following code to Controller. 

        [HttpPost]

        public JsonResult Create(List<TimeEntryDetail> timeentrydetails)

        {

           using (DB_TechAvidusEntities db = new DB_TechAvidusEntities())

            {

                if (timeentrydetails == null)

                {

                    timeentrydetails = new List<TimeEntryDetail>();

                }

                foreach (TimeEntryDetail detail in timeentrydetails)

                {

                    db.TimeEntryDetails.Add(detail);

                }

                int insertedRecords = db.SaveChanges();

                return Json(insertedRecords,JsonRequestBehavior.AllowGet);



            }

        }


       




 

Previous Post
Next Post
Related Posts

No comments:

Post a Comment