我的问题是将模型返回给控制器... 我有一个烹饪食谱网站。和两个模型
public class FeedBackListViewModel
{
public int FeedBackID { get; set; }
public string FoodName{ get; set; }
public List<StepModel> Steps { get; set; }
}
public class Food
{
public int ID {get;set;}
public string FoodName { get; set; }
public string Time { get; set; }
public List<StepModel> Steps { get; set; }
}
public class StepModel
{
public int StepID {get;set;}
public int StepNo { get; set; }
public string StepDetail { get; set; }
public bool Achived { get; set; }
}
public IActionResult Edit(int id)
{
// Imagine i have got a Food[0].Steps{Step1, Step2, Step 3}
each food has different number of Steps.
return View(Food[0]);
}
cshmtl文件...我简化了代码以便于阅读
@model FeedBackListViewModel
<form asp-action="Edit">
<input asp-for="FoodName " class="form-control" />
@foreach (var item in Model.Steps)
{
<tr>
<td>@Html.DisplayFor(model => item.StepID)</td>
<td>@item.StepNo</td>
<td>
<input type="text" id="@item" value="@item.StepDetail" />
</td>
<td><select asp-for="@item.Achivmed">
<option value = yes> Yes </option>
<option value = No> No </option>
</select>
</td>
</tr >
}
[HttpPost]
public IActionResult Edit(FeedBackListViewModel viewModel)
{
// I got my foodName detail correct but Steps are always null.
// I can't retrieve changes on steps.
return View();
}
答案 0 :(得分:-1)
请尝试以下。我认为Steps
初始化时未初始化FeedBackListViewModel
。
公共类FeedBackListViewModel
{
public int FeedBackID {get;组; }
公共字符串FoodName {get;组; }
公开列表步骤{get;组; }
public FeedBackListViewModel()
{
Steps = new List<StepModel>();
}
}
答案 1 :(得分:-1)
首先,我看不到将数据注入到集合中的代码。
public class FeedBackListViewModel
{
public int FeedBackID { get; set; }
public string FoodName{ get; set; }
public List<StepModel> Steps { get; set; } = new List<StepModel>();
}
还有,这里有错字
<select asp-for="@item.Achivmed">
再试一次!