如何在模型中发送列表 - AngularJS

时间:2016-07-12 00:41:38

标签: angularjs asp.net-mvc

我的模型有问题。

我需要向控制器发送另一个对象列表,但我不知道如何使用AngularJS创建此对象。 我有三个输入字段,homePhone,手机和联系人,所有字段都是关于电话,我的ClientModel有一个电话列表。我想要做的是获取这三个字段并包含在客户端模型中的列表中。

**MVC Model "Client"**

    public int Id { get; set; }
    public string Name { get; set; }
    public string Email{ get; set; }
    public IEnumerable<Phone> Phones { get; set; }

**MVC Model "Phone"**

    public int PhoneId { get; set; }
    public int ClientId { get; set; }
    public int PhoneType { get; set; }
    public string Number { get; set; }

查看

<div class="form-group col-lg-4">
    <label>Home Phone</label>
    <input class="form-control" ng-model="?">
</div>

<div class="form-group col-lg-4">
    <label>Cellphone</label>
    <input class="form-control" ng-model="?">
</div>

<div class="form-group col-lg-4">
    <label>Contact Phone</label>
    <input class="form-control" ng-model="?">
</div>

<button class="btn btn-primary" style="float: right" ng-click="saveClient(client)">Confirmar</button>

控制器JS

    $scope.saveClient = function(client) {
            clientesAPI.saveCliente(client).success(function() {
                alert('OK');
            }).error(function () {
                alert('Error');
            });`enter code here`
        }

3 个答案:

答案 0 :(得分:1)

您可以做的是在JS中创建实际的构造函数,并始终为您当前的服务器端MVC模型建模。

所以会看起来像这样...

angular.module('app', [])
  .factory('Client', function() {
    return Client;

    function Client() {
      this.id = 0;
      this.name = '';
      this.email = '';
      this.phones = [];
    }

    Client.prototype.init = function(client) {
      this.id = client.id;
      this.name = client.name;
      this.email = client.email;
      this.phones = [];
    }

  })
  .factory('Phone', function() {
    return Phone;

    function Phone() {
      this.phoneId = 0;
      this.clientId = 0;
      this.phoneType = 'Default Phone Type';
      this.number = 0;
    }

    Phone.prototype.init = function(phone) {
      this.phoneId = phone.phoneId;
      this.clientId = phone.clientId;
      this.phoneType = phone.phoneType;
      this.number = phone.number;
    }
  })
  .factory('clientService', function($http, $log, Client, Phone) {
    var service = {
      getClient: getClient,
      saveClient: saveClient
    };

    return service;

    //////////////////////////

    function getClient() {
      return $http.get('clientApi')
        .then(success)
        .catch(error)

      // This is where defining actual JS Quote unQuote Classes comes in handy
      function success(response) {
        var clients = response.data;
        angular.forEach(clients, function(client) {
          client = new Client().init(client);

          angular.forEach(client.phones, function(phone) {
            phone = new Phone().init(phone);
          })
        })

        return clients;
      }

      function error(response) {
        $log.error('Error getting Clients: ' + response.data);
      }
    }

    function saveClient(client) {

      return $http.post('clientApi', client)
        .then(success)
        .catch(error)

      // This is where defining actual JS Quote unQuote Classes comes in handy
      function success(response) {
        $log('Saved Client Successfully');
      }

      function error(response) {
        $log.error('Error saving Client: ' + response.data);
      }
    }
  })
  // I would use Controller As Syntax normally
  .controller('clientController', function($scope, clientService, Client, Phone) {
    $scope.client = new Client();
    $scope.client.phones.push(new Phone());
    $scope.savedClient;

    $scope.saveClient = function() {

      $scope.savedClient = $scope.client;
      alert('Yeah we saved some data!!');
      //Unconmment this to access the real service, Nowhere to call here :-)
      //clientService.saveClient($scope.client);
    };
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="clientController">
    <!-- Use ngRepeat to simplify things a bit -->
    <div class="form-group col-lg-4" ng-repeat="phone in client.phones track by phone.phoneId">
      <label>{{phone.phoneType}}</label>
      <input class="form-control" ng-model="phone.number">
    </div>

    <!-- You will already have access to the updated model in you controller -->
    <button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmation</button>

    <!--Display Saved Data-->
    <pre>{{savedClient | json}}</pre>
  </div>
</div>

出于几个原因,我喜欢这种方法的想法。

  1. 您可以在控制器中新建客户端或电话,并在Angular尝试渲染它们时知道某个或预期的模型属性。 (这可以避免恼人的client.phones.phoneId没有定义错误)

  2. 您的模型定义现在位于房屋JS侧的一个位置。即使这看起来像重复......好吧,但你必须在某个地方定义它,无论如何都要将它发送回服务器。所以我更喜欢在一个可重复使用的地方做这件事。

  3. 当您将模型属性输出到控制台时,您将获得客户端和电话阵列。这让我感觉很好: - )

  4. 这对你的问题来说有点过分,但我喜欢这种前端建模方法的干净感觉。

答案 1 :(得分:0)

您可以为模型创建新对象,并在那里添加手机属性。

查看

<div class="form-group col-lg-4">
    <label>Home Phone</label>
    <input class="form-control" ng-model="homePhone">
</div>

<div class="form-group col-lg-4">
    <label>Cellphone</label>
    <input class="form-control" ng-model="cellPhone">
</div>

<div class="form-group col-lg-4">
    <label>Contact Phone</label>
    <input class="form-control" ng-model="contactPhone">
</div>

<button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmar</button>

<强>控制器

$scope.saveClient = function() {
    var phones = [
       {ClientId: $scope.client.Id, PhoneType: 1, Number: $scope.homePhone},
       {ClientId: $scope.client.Id, PhoneType: 2, Number: $scope.cellPhone},
       {ClientId: $scope.client.Id, PhoneType: 3, Number: $scope.contactPhone}
    ]; // Not sure about the PhoneTypes. There are multiple ways to implement this, I'll leave it up to you.
    var data = {
       Id: $scope.client.Id,
       Name: $scope.client.Name,
       Email: $scope.client.Email,
       Phones: phones
    };    
    clientesAPI.saveCliente(data).success(function() {
        alert('OK');
    }).error(function () {
        alert('Error');
    });
};

答案 2 :(得分:0)

首先,您需要为视图定义ng-model,假设 -

element_id

现在你可以创建一个json对象并发布它,然后在服务器端你可以通过for-each loop访问所有手机 - 在你的控制器内 -

string querySQL="SELECT * FROM elements Where element_id=@id";
SqlCommand cmd = new SqlCommand(querySQL, con) // con is the Connection
cmd.Parameters.AddWithValue("@id", random_anumber);
// Get data using Adapter

现在你可以使用$ http服务发布

<input class="form-control" ng-model="hPhone">
<input class="form-control" ng-model="cellPhone">
<input class="form-control" ng-model="contactPhone">