ASP.net MVC5 - For循环发布单项而不是集合

时间:2014-07-07 17:00:13

标签: c# asp.net asp.net-mvc controller

我正在创建一个新的食谱条目表格,我发现了两个有趣的问题:

  1. 成分不会发布到食谱集合中,
  2. 当我将参数设置为集合时,表单将仅发布单个成分并发送null。
  3. 理想情况下,我希望成分集合在配方项目下,但我会满足于只是让成分集合写入参数。

    以下是两个模型(由实体框架生成):

    配方:

        public int recipeId { get; set; }
    
        [Required]
        [StringLength(255)]
        [DisplayName("Name")]
        public string name { get; set; }
    
        [DisplayName("Category")]
        public int? mealCategoryId { get; set; }
    
        [DisplayName("Preperation Time")]
        public int? prepTime { get; set; }
    
        [DisplayName("Cook Time")]
        public int? cookTime { get; set; }
    
        [DisplayName("Stand Time")]
        public int? standTime { get; set; }
    
        [DisplayName("Serving Size")]
        public int? servingSize { get; set; }
    
        [DisplayName("Status")]
        public int recipeStatusId { get; set; }
    
        [DisplayName("Description")]
        [UIHint("Multiline")]
        public string description { get; set; }
    
        public virtual ICollection<Direction> Directions { get; set; }
    
        public virtual ICollection<Image> Images { get; set; }
    
        public virtual ICollection<Ingredient> Ingredients { get; set; }
    
        public virtual MealCategory MealCategory { get; set; }
    
        public virtual ICollection<Nutrition> Nutritions { get; set; }
    
        public virtual ICollection<Rating> Ratings { get; set; }
    
        public virtual RecipeStatus RecipeStatus { get; set; }
    }
    

    成分:

    public partial class Ingredient
        {
            public int ingredientId { get; set; }
    
            public int? recipeId { get; set; }
    
            public int? subCategoryId { get; set; }
    
            public int measurementId { get; set; }
    
            public int amount { get; set; }
    
            public virtual Recipe Recipe { get; set; }
    
            public virtual SubCategory SubCategory { get; set; }
    
            public virtual Measurement Measurement { get; set; }
    
        }
    

    查看代码:

       <div class="form-horizontal">
            <h4>Ingredients</h4>
            <hr />
            <table class="table IngredientList">
                <tr>
                    <th>
                        @Html.LabelFor(model => model.Recipe.Ingredients)
                    </th>
                    <th>
                        @Html.LabelFor(model => model.SelectedMeasurementId)
                    </th>
                    <th>
                        @Html.Label("Amount")
                    </th>
                </tr>
    
                @for (int i = 0; i < Model.Recipe.Ingredients.Count; i++)
                {
                    <tr>
                        <td>
                            @Html.DropDownListFor(m => Model.Recipe.Ingredients.ElementAt(i).ingredientId, Model.SubIngredients, new { @class = "form-control input-block-level" })
                        </td>
                        <td>
                            @Html.DropDownListFor(m => Model.Recipe.Ingredients.ElementAt(i).measurementId, Model.Measurements, new { @class = "form-control input-block-level" })
                        </td>
                        <td>
                            @Html.TextBoxFor(m => Model.Recipe.Ingredients.ElementAt(i).amount, new { @class = "form-control input-block-level" })
                        </td>
                    </tr>
                }
    
            </table>
    </div>
    

    控制器:

       [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Recipe recipe, int SelectedCategoryId, List<Ingredient> Ingredients)
    
        {
            recipe.mealCategoryId = SelectedCategoryId;
            recipe.recipeStatusId = 1;
    
            if (ModelState.IsValid)
            {
                dbContext.Entry(recipe).State = EntityState.Added;
                dbContext.SaveChanges();
                return RedirectToAction("Details", new {id = recipe.recipeId});
            }
    
            return View(recipe);
        }
    

    因此,如果我将参数设置为List Ingredients,则返回null。如果我将它设置为成分成分,那么我只得到四种成分中的第一种。 (我将模型设置为在加载时创建4个成分记录。)

    我的问题是:如何让它通过成分集合?

    修改

    我已确认该请求正在发送所有4种成分。这似乎是绑定的问题。

1 个答案:

答案 0 :(得分:3)

创建自己的ViewModel来保存数据,不要使用Entity Frameworks预生成的类进行模型绑定。这是概念证明的一个非常基本的例子

public class Recipe
{
  public int RecipeId {get; set;}
  public List<Ingredients> Ingredient {get; set;}
} 

public class Ingredients
{
  public string Name {get; set;}
  public string Amount {get; set;}
}

public ActionResult Index()
{
   Recipe model = new Recipe();
   model.RecipeId = 1;
   model.Ingredient = new List<Ingredients>();//Better if done inside Constructor

   model.Ingredient.Add(new Ingredients{Name = "Salt", 
                                        Amount = "A Pinch"});
   model.Ingredient.Add(new Ingredients{Name = "Hot Sauce", 
                                        Amount = "HOT HOT HOT!"});   
  return View(model);
}

查看

@Html.TextBoxFor(x => x.RecipeId)

  for (int i = 0; i < Model.Ingredient.Count; i++)
    {
          @Html.TextBoxFor(modelItem => Model.Ingredient[i].Name)
          @Html.TextBoxFor(modelItem => Model.Ingredient[i].Amount)
    }

发布它并将绑定