剃刀形式与列表

时间:2016-11-20 11:52:02

标签: c# asp.net-mvc asp.net-mvc-4 razor

MVC新手,只是努力从List<>中检索我的表单数据。在我的控制器中,我能够正确获取我的名称值(食谱名称),但无法获得成分名称值,总是返回为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; }
}

查看

@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);
}

1 个答案:

答案 0 :(得分:0)

  1. 是类Ingredients的属性,类型为Recipe
  2. 您发布CreateEdit的操作有一个参数List<Ingredient>
  3. 要绑定列表对象,我们需要为每个项目提供索引。例如

    Recipe

    请阅读此链接 - http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/以便更好地理解这一点。