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