【问题标题】:Insert data into multiple tables using Ajax in ASP.NET MVC?在 ASP.NET MVC 中使用 Ajax 将数据插入多个表?
【发布时间】:2017-10-06 21:54:36
【问题描述】:

我有两张桌子EmployeesContacts

员工

  • 员工 ID
  • 姓名
  • 年龄
  • 军人身份
  • 婚姻状况

联系人

  • 联系人 ID
  • 电话
  • 电子邮件
  • EmpID //有外键和员工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>

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

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

谢谢

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 和你的要求一样吗?
    • 我想问你这个问题
    猜你喜欢
    • 2013-02-11
    • 2017-08-12
    • 1970-01-01
    • 2018-11-21
    • 2021-10-09
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    相关资源
    最近更新 更多