2016-11-20 57 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/爲了更好的理解。