Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor forms with lists

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);
}
like image 849
Sanchez89 Avatar asked Mar 21 '26 23:03

Sanchez89


1 Answers

  1. Ingredients is a property of class Recipe and is of type List<Ingredient>.
  2. The action to which you are posting CreateEdit has a parameter 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.

like image 185
Yasser Shaikh Avatar answered Mar 24 '26 12:03

Yasser Shaikh