1

我有 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;}
}

二形式:

   <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>

三、问题:

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

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

最后注:

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

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

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

谢谢布莱斯!!!

4

1 回答 1

4

似乎您构建的对象可能提交不正确。这是一个 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.
  }
});
于 2013-03-11T16:27:15.133 回答