0
新来的MVC,只是努力从列表中检索我的表格数据<>。在我的控制器中,我能够正确地获取我的名称值(配方名称),但无法获取“成分名称”值,始终返回为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; }
}
VIEW
@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);
}
看看这个:http://stackoverflow.com/a/23553225/3585278 – Danieboy
你不能在视图中使用'.FirstOrDefault()' - 你需要使用'for'循环或自定义的'EditorTemplate' '成分' - 参考[这个答案](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943)。但是,如果你只需要一种“配料”,为什么使用'List''? –
@Danieboy谢谢,解决了我的问题 – Sanchez89