在ASP.NET MVC中使用Ajax将数据插入多个表中?

时间:2017-05-08 19:03:38

标签: asp.net ajax asp.net-mvc asp.net-mvc-5 entity-framework-6

我有两张表EmployeesContacts

员工

  • 员工-ID
  • 名称
  • 年龄
  • 军事状态
  • 婚姻状态

联系人

  • 的ContactID
  • 电话
  • 电子邮件
  • EmpID //具有Employee-ID
  • 的外键

一名员工有很多联系人

我有一个表单页面,用于使用Ajax添加具有联系人详细信息的新员工。在此代码中,我刚刚添加了新员工,但我还希望同时将联系人详细信息添加到Contacts列表中:



@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>
&#13;
&#13;
&#13;

这是我的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");
    }
}

我尝试了几种方法,但仍然没有得到解决方案。

由于

1 个答案:

答案 0 :(得分:3)

更好的方法是创建两个模型的视图模型,如

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         
}

然后在AJAX请求中按照要求对数据进行串行化。例如

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

然后在您的控制器中,使用ViewModel填充您的实体,然后使用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();

}