MVC新手,只是努力从List<>中检索我的表单数据。在我的控制器中,我能够正确获取我的名称值(食谱名称),但无法获得成分名称值,总是返回为NULL?
以下是我项目中的一些代码段。
MODEL
public class Recipe
{
[Required]
public string Name { get; set; }
public List<Ingredient> Ingredients { get; set; }
public Recipe()
{
Ingredients = new List<Ingredient>()
{
new Ingredient()
};
}
}
public class Ingredient
{
public string Name { get; set; }
}
查看
@using (Html.BeginForm("CreateEdit", "Recipe"))
{
@Html.ValidationSummary()
<div class="form-group">
@Html.LabelFor(x => x.Name, "Name")
@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Name)
</div>
<h2>Ingredient(s)</h2>
<div class="form-group">
@Html.LabelFor(x => x.Ingredients.FirstOrDefault().Name, "Name")
@Html.TextBoxFor(x => x.Ingredients.FirstOrDefault().Name, new { @class = "form-control" })
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" text="submit" />
</div>
}
CONTROLLER
[HttpPost]
public ActionResult CreateEdit(Recipe recipe)
{
var recipeName = recipe.Name // <--- Works
var ingredientName = recipe.Ingredients.FirstOrDefault().Name; //<--- NULL value
return View(recipe);
}
答案 0 :(得分:0)
择
是类Ingredients
的属性,类型为Recipe
。 List<Ingredient>
。要绑定列表对象,我们需要为每个项目提供索引。例如
Recipe
请阅读此链接 - http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/以便更好地理解这一点。