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

Ahmed Mulu 1 Reputation point
2022-09-07T07:00:28.947+00:00

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);  
    }  
}  

}

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,385 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Lan Huang-MSFT 28,126 Reputation points Microsoft Vendor
    2022-09-08T08:31:39.91+00:00

    Hi @Ahmed Mulu ,
    I suggest you breakpoint to check for errors. You'd better provide a small example that reproduces the problem.
    You can refer to the demo I wrote:
    239012-1.png

    <body>   
        <div title = "PostPortion">   
        <input type = "text" id = "txtPlace" placeholder = "Place"/>   
            <input type = "text" id = "txtDriver"placeholder = "Driver"/>   
            <input type = "text" id = "txtTestType" placeholder = "TestType"/>   
            <input type = "button" id = "btnPost" value = "Post Data" />   
        </div>  
        </body>   
    

    public ActionResult Index()  
            {  
                return View();  
            }  
            [HttpPost]  
            public JsonResult AjaxPostCall(Deta deta)  
            {  
                Deta deta1 = new Deta  
                {  
                    Place = deta.Place,  
                    Driver = deta.Driver,  
                    TestType = deta.TestType,  
                };  
                return Json(deta1, JsonRequestBehavior.AllowGet);  
            }  
    

    238946-demo.gif
    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.