2016-11-20 59 views
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); 
} 
+1

看看这个:http://stackoverflow.com/a/23553225/3585278 – Danieboy

+1

你不能在视图中使用'.FirstOrDefault()' - 你需要使用'for'循环或自定义的'EditorTemplate' '成分' - 参考[这个答案](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943)。但是,如果你只需要一种“配料”,为什么使用'List ''? –

+1

@Danieboy谢谢,解决了我的问题 – Sanchez89

回答

0
  1. IngredientsRecipe类的属性和是List<Ingredient>类型。
  2. 您要发布的操作CreateEdit具有参数Recipe

要绑定列表对象,我们需要为每个项目提供一个索引。例如像

<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> 

阅读此链接 - http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/为了更好的理解。