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);
}
Ingredients is a property of class Recipe and is of type List<Ingredient>. Recipe.To bind list objects we need to provide an index for each items. Like for example
<form method="post" action="/Home/CreateEdit">
<input type="text" name="recipe.Ingredients[0].Name" value="Red Sauce" />
<input type="text" name="recipe.Ingredients[1].Name" value="White Sauce" />
</form>
Read this link - http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/ to understand this better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With