AngularJs绑定表单提交集合

时间:2013-03-11 16:06:04

标签: angularjs

我有2张桌子:(1)用餐(2)蔬菜。基本上在表单提交中,用户选择2个蔬菜添加到新创建的膳食中。

予。服务器端的模型创建:

 public class Meal{

    public Meal(
       Vegatables = new List<Vegatable>();
    }

    public int Id {get; set;}
    public string Name {get; set;}
    public virtual ICollection<Vegatable> Vegatables {get; set;}
}

 public class Vegatable{

    public Vegatable(
       Meals = new List<Meal>();
    }

    public int Id {get; set;}
    public string Name {get; set;}
    public virtual ICollection<Meal> Meals {get; set;}
}

II表格:

   <div ng-controller="MealCtrl>
   <input  type="text" ng-model="meal"></select>

   <label>Choose Vegatable 1</label>
   <div ng-controller="VegatableCtrl>
   <select id="vegatable1" ng-model="vegatable" ng-options="vegatable.Name for vegatable in vegatables"></select>
   </div>      

   <label>Choose Vegatable 2</label>
   <div ng-controller="VegatableCtrl>
   <select id="vegatable2" ng-model="vegatable" ng-options="vegatable.Name for vegatable in vegatables"></select>
   </div> 

  </div>

III。问题:

显然,当我在locals窗口中查看我的服务器控制器的POST方法时,没有为Meal类的vegatable集合分配值。

关于如何在保存到服务器之前将vegtables添加到$ scope.meal的任何想法?

最后注意事项:

由于这是一个多对多关系,因此会有一个连接表。这对POST方法有何影响?

已解决 - 像往常一样:BLESH拯救!!

有一件事我认为我做错了就是在选择中使用VegatableCtrl。我现在看到$ scope.Vegatables的填充实例应该在MealCtrl中,并使用MealCtrl来填充Vegatables的选择。

谢谢Blesh !!!

1 个答案:

答案 0 :(得分:4)

似乎您的构建对象可能无法正确提交。 Here is a plunker显示了MVC方法应该接受的对象的构建。

这是HTML:

<form ng-controller="MealCtrl" name="MealForm" ng-submit="submitMeal()">
  <select ng-model="selectedMeal" ng-options="meal.Name for meal in Meals"></select><br/>

  <label>Choose Vegatable 1
  <select ng-model="selectedVeggie1" ng-options="vegetable.Name for vegetable in vegetables"></select></label>
  <br/>

  <label>Choose Vegatable 2
  <select ng-model="selectedVeggie2" ng-options="vegetable.Name for vegetable in vegetables"></select></label>
  <br/>

  <button type="submit">Submit</button>
</form>

和示例Angular控制器:

app.controller('MealCtrl', function($scope) {
  $scope.Meals = [
    { Id: 1, Name: 'Meal 1' },
    { Id: 2,  Name: 'Meal 2' },
    { Id: 3, Name: 'Meal 3' }
  ];

  $scope.vegetables = [
    {Id: 100, Name: 'Broccoli' },
    {Id: 101, Name: 'Zucchini' },
    {Id: 102, Name: 'Green Beans' },
    {Id: 103, Name: 'Brussel Sprouts'}
  ];

  $scope.submitMeal = function (){
    //build the meal
    var meal = angular.copy($scope.selectedMeal);
    meal.Vegetables = [
      angular.copy($scope.selectedVeggie1),
      angular.copy($scope.selectedVeggie2)
      ];
    console.log(meal);
    //TODO: submit via ajax.
  }
});