Insert data into multiple tables using Ajax in ASP.NET MVC?

ajax asp.net asp.net-mvc asp.net-mvc-5 entity-framework-6

Question

I have two tables Employees and Contacts.

Employees:

  • Employee-ID
  • Name
  • Age
  • Military-status
  • Marital-status

Contacts:

  • ContactID
  • Phone
  • Email
  • EmpID //Has foreign-Key with Employee-ID

One employee has many contacts

I have form page to add a new employee with contact details using Ajax. In this code I have just added the new employee, but I want to also add the contact details into the Contacts tabls at the same time:

@using Compu_MVC.Models;
@model Tuple<Emp, Cont>

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend></legend>

        <div class="editor-label">
            Employee Name
        </div>
        <div class="editor-field">
            @Html.EditorFor(Tuple => Tuple.Item1.Name)
            @Html.ValidationMessageFor(Tuple => Tuple.Item1.Name)
        </div>

        <div class="editor-label">
            Age
        </div>
        <div class="editor-field">
            @Html.EditorFor(Tuple => Tuple.Item1.Age)
            @Html.ValidationMessageFor(Tuple => Tuple.Item1.Age)
        </div>

        <div class="editor-label">
            DepartmentName
        </div>
        <div class="editor-field">
         @Html.DropDownListFor(c => c.Item1.DepID, ViewData["Department"] as SelectList)          
        </div>
        <div class="editor-label">
            MilitaryStatus
        </div>
        <div class="editor-field">
            @Html.EditorFor(Tuple => Tuple.Item1.MilitaryStatus)
            @Html.ValidationMessageFor(Tuple => Tuple.Item1.MilitaryStatus)
        </div>
        <div class="editor-label">
            MaritalStatus
        </div>
        <div class="editor-field">
            @Html.EditorFor(Tuple => Tuple.Item1.MaritalStatus)
            @Html.ValidationMessageFor(Tuple => Tuple.Item1.MaritalStatus)
        </div>
        <div class="editor-label">
            Job
        </div>
        <div class="editor-field">
            @Html.EditorFor(Tuple => Tuple.Item1.Job)
            @Html.ValidationMessageFor(Tuple => Tuple.Item1.Job)
        </div>
        <div class="editor-label">
            Gendar
        </div>
        <div class="editor-field">
            @Html.EditorFor(Tuple => Tuple.Item1.Gendar)
            @Html.ValidationMessageFor(Tuple => Tuple.Item1.Gendar)
        </div>
        <div class="editor-label">
            IDNumber
        </div>
        <div class="editor-field">
            @Html.EditorFor(Tuple => Tuple.Item1.IDNumber)
            @Html.ValidationMessageFor(Tuple => Tuple.Item1.IDNumber)
        </div>
        <div class="editor-label">
            Address
        </div>
        <div class="editor-field">
            @Html.EditorFor(Tuple => Tuple.Item2.Phone)
            @Html.ValidationMessageFor(Tuple => Tuple.Item2.Phone)
        </div>
        <div class="editor-label">
            Email
        </div>
        <div class="editor-field">
            @Html.EditorFor(Tuple => Tuple.Item2.Email)
            @Html.ValidationMessageFor(Tuple => Tuple.Item2.Email)
        </div>
        <div class="editor-label">
            Email
        </div>
        <div class="editor-field">
            @Html.EditorFor(Tuple => Tuple.Item2.Address)
            @Html.ValidationMessageFor(Tuple => Tuple.Item2.Address)
        </div>
        <p>           
            <input id="btnCreate" type="submit" name="Create" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Close", "Index")
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/jquery-ui-1.10.2/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/jquery-ui-1.10.2/ui/minified/jquery-ui.min.js")" type="text/javascript"></script>

<script type="text/javascript">
    
    $(function () {
        $("#btnCreate").click(function () {
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: '{Name: "' + $("#Name").val()
                + '"Age: "' + $("#Age").val()
                + '"MilitaryStatus:"'+ $("#MilitaryStatus").val()
                + '"MaritalStatus: "' + $("#MaritalStatus").val()
                + '"Job: "' + $("#Job").val()
                + '"Gendar: "' + $("#Gendar").val()
                + '"IDNumber: "' + $("#IDNumber").val()
                + '"MaritalStatus: "' + $("#MaritalStatus").val() +'" }',

                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    });


    //$('#c').click(function () {
    //    alert('ok')
    //    $.ajax({
    //        url: '/Employe/Create',
    //        dataType: "json",
    //        type: "POST",
    //        contentType: 'application/json; charset=utf-8',
    //        data: JSON.stringify({ Emp: { Name: 'Rintu', Age: '12343' } }),
    //        async: true,
    //        processData: false,
    //        cache: false,
    //        success: function (data) {
    //            alert(data);
    //        },
    //        error: function (xhr) {
    //            alert('error');
    //        }
    //    });
    //});  

    function SaveEmployee() {
        debugger;
        //var Name = $("#Name").val();
        //var Age = $("#Age").val();
        //var DepartmentID = $("#Department.DepartmentID").val();
        //var MilitaryStatus = $("#MilitaryStatus").val();
        //var MaritalStatus = $("#MaritalStatus").val();
        //var Job = $("#Job").val();
        //var Gendar = $("#Gendar").val();
        //var IDNumber = $("#IDNumber").val();


        //var Employee = {
        //    "Name": Name, "Age": Age,
        //    "DepartmentName.DepartmentID": DepartmentName.DepartmentID, "MilitaryStatus": MilitaryStatus, "MaritalStatus": MaritalStatus,
        //    "Job": Job, "Gendar": Gendar, "IDNumber": IDNumber
        //};

        //$.post("/Employe/Create", Employee,
        //    function (data) { if (data == 0) { location = location.href; } }, 'json');

       
            /*POST*/

               


    } 
</script>

This is my EmployeeController :

public class EmployeController : Controller
{
    DynamicEntities db = new DynamicEntities();

    // GET: Employe
    public ActionResult Index() //Record Select 
    {
        List<Employee> EmployeeDatas = db.Employees.OrderByDescending(x => x.EmployeeID).ToList<Employee>();
        return View(EmployeeDatas);           
    }

    [HttpGet]
    public PartialViewResult Create()   //Insert PartialView  
    {
        DynamicEntities db = new DynamicEntities();
        var contrs = db.Departments.ToList();
        ViewData["Department"] = new SelectList(contrs, "DepartmentID", "DepartmentName");
        return PartialView(new Emp());
    }

    [HttpPost]
    public ActionResult Create(Employee emp) // Record Insert  
    {
        DynamicEntities db = new DynamicEntities();
        db.Employees.Add(emp);
        db.SaveChanges();

        return Redirect("Index");
    }
}

I tried several ways but still not get the solution .

Thanks

1
0
5/8/2017 7:39:39 PM

Accepted Answer

Better approach is to create viewmodel of your both model like

public class EmployeesContactViewModel
{
    public string Name{ get; set; }
    public int Age{ get; set; } 
    public bool MilitaryStatus{ get; set; }
    public string Phone{ get; set; } 
    public string Email{ get; set; }
    // etc etc rest of your data         
}

and after that in AJAX request serialaze your data as per requirement. For Example

var EmployeesContact={  
   Name:$("#Name").val(),
   Age:$("#Age").val(),
   MilitaryStatus:$("#MilitaryStatus").val(),
   Phone:$("#Phone").val(),
   Email:$("#Email").val()
   // etc etc rest of your data 
};
$("#btnCreate").click(function() {
  $.ajax({
    type: "POST",
    url: "/Home/Add",
    data: EmployeesContact,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response) {
      alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
    },
    failure: function(response) {
      alert(response.responseText);
    },
    error: function(response) {
      alert(response.responseText);
    }
  });
});

Then in your controller, use your ViewModel to populate your entities, then insert using EF:

[HttpPost]
public ActionResult Add(EmployeesContactViewModel model)
{
     var objEmployee = new Employee{
          Name = model.Name,
          Age= model.Age,
          MilitaryStatus= model.MilitaryStatus,
     };

     var objContact= new Contact{
          Phone= model.Phone,
          Email= model.Email
     };

     //etc for your other entities

     using (var context = new DynamicEntities )
     {
          context.Employee.Add(objEmployee);
          objContact.EmployeeId = Employee.EmployeeId;
          context.Contact.Add(objContact);
          context.SaveChanges();    
     }

     //whatever you want to do here for the result, maybe direct to new controller
     //or return view
     return View();

}
3
5/8/2017 9:20:23 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow