New to MVC and just struggling with retrieving my form data from a List<>. In my controller, I am able to get my Name value (recipe name) correctly but cannot get the Ingredient Name value, always coming back as NULL?
Below are some code snippets from my project.
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);
}