レシピを正しく入力する方法を実装しようとしていますが、これまでのところ次のとおりです。
レシピ.cs
public class Recipe
{
[Key]
public int RecipeId { get; set; }
[Required]
public string Name { get; set; }
public string Subtitle { get; set; }
public int Serving { get; set; }
public string Instructions { get; set; }
public virtual ICollection<Ingredient> Ingredients
}
成分.cs
public class Ingredient
{
[Key]
public int IngredientId { get; set; }
public string Name { get; set; }
public string Amount { get; set; }
public virtual ICollection<Recipe> Recipes { get; set; }
}
私のフォームでは、必要に応じて JavaScript レンダリングで新しいフィールドのペアを使用して、成分をインラインで追加したいと考えています。
(ViewModel は Recipe のインスタンスを保持するクラスに他なりません)
作成.cshtml
@model Vineyard.WebUI.Areas.Admin.Models.RecipeViewModel
<div class="span9">
<h2>Create a new Recipe</h2>
@using (@Html.BeginForm("Create", "Recipes", FormMethod.Post))
{
<fieldset>
@Html.LabelFor(r => r.Recipe.Name)
@Html.TextBoxFor(r => r.Recipe.Name)
</fieldset>
<fieldset>
@Html.LabelFor(r => r.Recipe.Subtitle)
@Html.TextBoxFor(r => r.Recipe.Subtitle)
</fieldset>
<div id="ingredients">
@Html.EditorFor(r => r.Recipe.Ingredients, "Ingredient")
</div>
<a href="#" id="addIngredient" class="btn btn-info">Add Ingredient</a>
<fieldset>
@Html.LabelFor(r => r.Recipe.Serving)
@Html.TextBoxFor(r => r.Recipe.Serving)
</fieldset>
<fieldset>
@Html.LabelFor(r => r.Recipe.Instructions)
@Html.TextAreaFor(r => r.Recipe.Instructions)
</fieldset>
<input type="submit" value="Save Recipe" />
}
</div>
共有/EditorTemplates/Ingredient.cshtml
@model Vineyard.Core.Entities.Ingredient
<div class="ingredient form-inline">
@Html.LabelFor(r => r.Amount)
@Html.TextBoxFor(r => r.Amount)
@Html.LabelFor(r => r.Name)
@Html.TextBoxFor(r => r.Name)
</div>
レンダリングされた HTML タフには、次のように表示されます。
<input id="Recipe_Ingredients_Amount" name="Recipe.Ingredients.Amount" type="text" value="">
これは、成分をコレクションのメンバーとして追加するのではなく、それ自体が完全なオブジェクトとして追加すると私が信じるように導きます。それを参照するインデックスを持つべきではありませんか?(これに基づくhttp://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3 )
コントローラーに戻されているモデルを見ると、Ingredients Part はnull
それで、私は疑問に思っています-ここで何が欠けているのか、間違っているのか、実際にコレクションを正しく設定するために変更することができますか? そこから、コントローラーで処理して、正しい形式で保存できます。