我试图实现一种如何正确输入食谱的方法,到目前为止,我有以下内容:
食谱.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>
Shared/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)
当我查看正在传递回控制器的模型时,成分部分是null
所以,我想知道 - 我在这里遗漏了什么或做错了什么,可以将其更改为实际正确填充集合?从那里,我可以在控制器中处理它,以正确的格式保存。