How to Save records to Master-detail tables in ASP.NET MVC 5

Viewed 60

I have Test and Deta(Details) table in DB. With Entity Framework 5 I have obtained a model so I have classes generated from it. I also created controllers and views for the Deta table. I can add, clear and delete the records before saving but finally, I can't to save the records.

Test table has (TestID, MissionCode, StartDate, EndDate) Deta table has (DetaId, TestType, TestDate, Driver, Place, TestID) I used the following script in the view to add, clear and save the record.

@section scripts{
    <script>
        //Show Modal.
        function addNewDeta() {
            $("#newDetaModal").modal();
        }
        //Add Multiple Order.
        $("#addToList").click(function (e) {
            e.preventDefault();

            if ($.trim($("#testType").val()) == "" || $.trim($("#testDate").val()) == "" || $.trim($("#driver").val()) == "" || $.trim($("#place").val()) == "") return;

            var testType = $("#testType").val(),
                testDate = $("#testDate").val(),
                driver = $("#driver").val(),
                place = $("#place").val(),
                detailsTableBody = $("#detailsTable tbody");

            var tstItem = '<tr><td>' + testType + '</td><td>' + testDate + '</td><td>' + driver + '</td><td>' + place + '</td><td><a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
            detailsTableBody.append(tstItem);
            clearItem();
        });
        //After Add A New Order In The List, Clear Clean The Form For Add More Order.
        function clearItem() {
            $("#testType").val('');
            $("#testDate").val('');
            $("#driver").val('');
            $("#place").val('');
        }
        // After Add A New Order In The List, If You Want, You Can Remove It.
        $(document).on('click', 'a.deleteItem', function (e) {
            e.preventDefault();
            var $self = $(this);
            if ($(this).attr('data-itemId') == "0") {
                $(this).parents('tr').css("background-color", "#ff6347").fadeOut(800, function () {
                    $(this).remove();
                });
            }
        });
        //After Click Save Button Pass All Data View To Controller For Save Database
        function saveDeta(data) {
            return $.ajax({
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                type: 'POST',
                url: "/Detas/SaveDeta",
                data: data,
                success: function (result) {
                    alert(result);
                    location.reload();
                },
                error: function () {
                    alert("Error!")
                }
            });
        }
        //Collect Multiple Order List For Pass To Controller
        $("#saveDeta").click(function (e) {
            e.preventDefault();

            var detaArr = [];
            detaArr.length = 0;

            $.each($("#detailsTable tbody tr"), function () {
                detaArr.push({
                    testType: $(this).find('td:eq(0)').html(),
                    testDate: $(this).find('td:eq(1)').html(),
                    driver: $(this).find('td:eq(2)').html(),
                    place: $(this).find('td:eq(3)').html()
                });
            });

            var data = JSON.stringify({
                missionCode: $("#missionCode").val(),
                startDate: $("#startDate").val(),
                endDate: $("#endDate").val(),
                deta: detaArr
            });

            $.when(saveDeta(data)).then(function (response) {
                console.log(response);
            }).fail(function (err) {
                console.log(err);
            });
        });
    </script>
}

This is the controller

namespace WebApplication2.Controllers
{
    public class DetasController : Controller
    {
        ETHADAMISEntities db = new ETHADAMISEntities();
        public ActionResult Index()
        {
            List<Test> DetaAndTest = db.Tests.ToList();
            return View(DetaAndTest);
        }
        public ActionResult SaveDeta(string missionCode, DateTime startDate, DateTime endDate, Deta[] deta)
        {
            string result = "Error! Test Detail Is Not Complete!";
            if (missionCode != null && startDate != null && endDate != null && deta != null)
            {
                var tstId = Guid.NewGuid();
                Test model = new Test
                {
                    TestID = tstId,
                    MissionCode = missionCode,
                    StartDate = startDate,
                    EndDate = endDate
                };
                db.Tests.Add(model);

                foreach (var item in deta)
                {
                    var id = Guid.NewGuid();
                    Deta O = new Deta
                    {
                        DetaId = id,
                        TestType = item.TestType,
                        TestDate = item.TestDate,
                        Driver = item.Driver,
                        Place = item.Place,
                        TestID = tstId
                    };
                    db.Detas.Add(O);
                }
                db.SaveChanges();
                result = "Success! Test with Detail Is Complete!";
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}

This is the view

@model IEnumerable<WebApplication2.Models.Test>
<br /><br />
<div class="panel panel-default">
    <div class="panel-heading">
        <div class="row">
            <h2 class="panel-title pull-left" style="margin-left:10px;">
                <strong>Test Details</strong>
            </h2>
            <button style="margin-right:10px" class="btn btn-primary pull-right" onclick="addNewDeta()">New Test</button>
        </div>
    </div>

    @*Receive All Database Data From Controller And Display Those Data In Client Side*@

    @if (Model.Count() != 0)
    {
        foreach (var item in Model)
        {
            <div class="panel-body">
                <table class="table table-striped table-responsive">
                    <tbody>
                        <tr>
                            <td>Mission Code : @item.MissionCode </td>
                            <td>Start Date : @item.StartDate </td>
                            <td>End Date : @item.EndDate</td>
                        </tr>
                        <tr>
                            <td colspan="3">
                                <table class="table table-bordered">
                                    <tbody>
                                        <tr>
                                            <th>Test Type</th>
                                            <th>Test Date</th>
                                            <th>Driver</th>
                                            <th>Place</th>
                                        </tr>
                                        @foreach (var deta in item.Detas)
                                        {
                                            <tr>
                                                <td>@deta.TestType</td>
                                                <td>@deta.TestDate</td>
                                                <td>@deta.Driver</td>
                                                <td>@deta.Place</td>
                                            </tr>
                                        }
                                    </tbody>
                                </table>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        }
    }
    else
    {
        <div class="panel-body">
            <h3 style="color:red;">Empty!</h3>
        </div>
    }
</div>

@*Desing Bootstrap Modal With Order Form*@

<div class="modal fade" id="newDetaModal">
    <div class="modal-dialog modal-lg" style=" width: 900px !important;">
        <div class="modal-content">
            <div class="modal-header">
                <a href="#" class="close" data-dismiss="modal">&times;</a>
                <h4>Add New Test</h4>
            </div>
            <form id="NewDetailForm">
                <div class="modal-body">
                    @*Test Details*@
                    <h5 style="color:#ff6347">Tests</h5>
                    <hr />
                    <div class="form-horizontal">
                        <input type="hidden" id="TestID" />
                        <div class="form-group">
                            <label class="control-label col-md-2">
                                Mission Code
                            </label>
                            <div class="col-md-4">
                                <input type="text" id="missionCode" name="missionCode" placeholder="Mission Code" class="form-control" />
                            </div>
                            <label class="control-label col-md-2">
                                Start Date
                            </label>
                            <div class="col-md-4">
                                <input type="text" id="startDate" name="startDate" placeholder="Start Date" class="form-control" />
                            </div>
                            <label class="control-label col-md-2">
                                End Date
                            </label>
                            <div class="col-md-4">
                                <input type="text" id="endDate" name="endDate" placeholder="End Date" class="form-control" />
                            </div>
                        </div>
                    </div>

                    @*Test Detail Details*@
                    <h5 style="margin-top:10px;color:#ff6347">Test Details</h5>
                    <hr />
                    <div class="form-horizontal">
                        <input type="hidden" id="DetaId" />
                        <div class="form-group">
                            <label class="control-label col-md-2">
                                Test Type
                            </label>
                            <div class="col-md-4">
                                <input type="text" id="testType" name="testType" placeholder="Test Type" class="form-control" />
                            </div>
                            <label class="control-label col-md-2">
                                Test Date
                            </label>
                            <div class="col-md-4">
                                <input type="datetime" id="testDate" name="testDate" placeholder="Test Date" class="form-control" />
                            </div>
                            <label class="control-label col-md-2">
                                Place
                            </label>
                            <div class="col-md-4">
                                <input type="text" id="place" name="place" placeholder="Place" class="form-control" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-md-2">
                                Driver
                            </label>
                            <div class="col-md-4">
                                <input type="text" id="driver" name="driver" placeholder="Driver" class="form-control" />
                            </div>
                            <div class="col-md-2 col-lg-offset-4">
                                <a id="addToList" class="btn btn-primary">AddToList</a>
                            </div>
                        </div>
                        <table id="detailsTable" class="table">
                            <thead>
                                <tr>
                                    <th style="width:30%">Test Type</th>
                                    <th style="width:20%">Test Date</th>
                                    <th style="width:25%">Driver</th>
                                    <th style="width:15%">Place</th>
                                    <th style="width:10%"></th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="reset" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button id="saveDeta" type="submit" class="btn btn-success">Save Test Detail</button>
                </div>
            </form>
        </div>
    </div>
</div>
0 Answers
Related