【发布时间】:2021-06-06 03:13:57
【问题描述】:
我有一个包含成分列表的 Recipe 对象,我创建了一个 AddRecipe 页面,其中有一个成分列表,我希望用户在创建时填充它。
问题是,我可以将东西添加到列表中,在调试器中我可以看到列表的长度增加了,我可以看到列表中的新成分,但是如果我添加一个新成分,它似乎会替换列表,或覆盖它,所以我不能像这样在该列表中存储超过 1 个东西
这是 AddRecipe.cshtml 代码:
<div class="row">
<div class="col">
<div class="form-group">
<table class="table table-striped border">
<tr class="table-secondary">
<th>
Name
</th>
<th>
Quantity
</th>
<th>
Price
</th>
<th>
Calories
</th>
</tr>
@foreach (var item in Model.Ingredients)
{
<tr>
<td>
@Html.DisplayFor(m => item.Name)
</td>
<td>
@Html.DisplayFor(m => item.Quantity)
</td>
<td>
@Html.DisplayFor(m => item.Price)
</td>
<td>
@Html.DisplayFor(m => item.Calories)
</td>
</tr>
}
</table>
</div>
</div>
<div class="col">
<div class="form-group">
<form method="post">
<div class="m-1"> Ingredient: <input type="text" name="ingredientName" /> </div>
<div class="m-1"> Amount: <input type="number" name="ingredientAmount" /> </div>
<div class="m-1"> Price: <input type="number" name="ingredientPrice" /> </div>
<div class="m-1"> Calories: <input type="number" name="ingredientCalories" /> </div>
<button asp-page-handler="AddNew">Add!</button>
</form>
</div>
</div>
</div>
这里是 .cshtml.cs 文件:
public class AddRecipeModel : PageModel
{
private readonly IApiClient _apiClient;
public AddRecipeModel(IApiClient apiClient)
{
_apiClient = apiClient;
}
[BindProperty]
public Recipe Recipe { get; set; }
public List<Ingredient> Ingredients { get; set; } = new List<Ingredient>();
// To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
return RedirectToPage("./Index");
}
public void OnPostAddNew(string ingredientName, int ingredientAmount, int ingredientPrice, int ingredientCalories)
{
Ingredient newIngredient = new Ingredient(ingredientName, ingredientPrice, ingredientAmount, ingredientCalories);
Ingredients.Add(newIngredient);
}
}
【问题讨论】:
-
这不是免费的编码资源,它是咨询资源。没有人会为你编码。你必须做一些研究,你会发现很多例子。
-
@Sergey 我真的找不到很多关于这个问题的例子或材料,我想出了这个解决方案,但我不确定为什么在添加新的时候它会重置我的成分列表.我不需要任何人为我编写代码,只需一个简单的方向即可开始调试或学习什么
标签: asp.net list asp.net-core razor action