通过AngularJS推送多个条目并将其保存在数据库中

时间:2016-04-20 21:19:36

标签: angularjs asp.net-mvc entity-framework-6

我很难将我在“$ scope.arr”中推送的多行保存到我的SQL Server数据库中。我在下面有我的代码并且它工作正常但是当我通过按“添加人员”按钮添加/推送一些条目后单击“保存到数据库”按钮时,它将具有空值的行传递给SQL Server数据库。请指导我在哪里犯错:

我也听说过使用angular.forEach循环,但我也很困惑。

我的模型类“TestModel.cs”在这里:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestProj.Models
{
    public class TestModel
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

我的MVC控制器在这里命名为TestController的Add方法:

[HttpPost]
public string AddPerson(TestModel test)
            using (TestContext db = new TestContext())
            {
                if (test != null)
                {
                    db.TestModels.Add(test);
                    db.SaveChanges();
                    return "Successful";
                }
                else
                {
                    return "Failed";
                }
            }
        }

我的AngularJS脚本:

var app = angular.module("TestApp", []);

app.controller("TestCtrl", function ($scope, TestService) {

    $scope.arr = [];

    $scope.addPerson = function () {
        var myobj = {
            FirstName: $scope.firstname,
            LastName: $scope.lastname
        }
        $scope.arr.push(myobj);
    };

    $scope.savePerson = function () {
        var TestData = TestService.AddPer($scope.arr);
        TestData.then(function (msg) {
            alert(msg.data);
        }, function () {
            alert('Error In Adding Person');
        });
    };

});

app.service("TestService", function ($http) {

    this.AddPer = function (person) {
        var response = $http({
            method: "post",
            url: "/Test/AddPerson",
            data: JSON.stringify(person),
            dataType: "json",
        });
        console.log(response);
        return response;
    }
});

我的Index.cshtml文件在这里:

<div ng-controller="TestCtrl">
    <form>
        FirstName: <input class="form-control" ng-model="firstname" /><br />
        LastName: <input class="form-control" ng-model="lastname" /><br />
        <button class="btn btn-success" ng-click="addPerson()">Add Person</button>
        <button class="btn btn-success" ng-click="savePerson()">Save To DB</button>

        <table class="table table-bordered">
            <tr>
                <th>S. No</th>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
            <tr ng-repeat="a in arr">
                <td>{{$index+1}}</td>
                <td>{{a.FirstName}}</td>
                <td>{{a.LastName}}</td>
            </tr>
        </table>
    </form>
</div>

<script src="~/Scripts/MyAngular/Module.js"></script>

我们将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

然后服务器端操作应该期望收集TestModel,您可以在那里List。如果您在参数之前[FromBody],则在将其发布到服务器之前不需要stringify数据。

<强>代码

[HttpPost]
public string AddPerson([FromBody] List<TestModel> test)
  using(TestContext db = new TestContext()) {
    test.forEach(t=> {
      if (t != null) {
          db.TestModels.Add(t);
          return "Successful";
      } else {
          return "Failed";
      }
    });
    db.SaveChanges(); //save context at the end, when no error occurs
  }
}

答案 1 :(得分:1)

问题在于我的服务器端代码,即我的C#控制器,这种方法有效:

[HttpPost]
        public void AddPerson(List<TestModel> test)
        {
            using (TestContext db = new TestContext())
            {
                foreach(var t in test) 
                {
                    if (t != null)
                    {
                        db.TestModels.Add(t);
                        Console.WriteLine("Success");
                    }
                }
                db.SaveChanges(); //save context at the end, when no error occurs
            }
        }