我有一个真正愚蠢的问题...我找不到答案,而且我有点羞于问... 我有一个名为 Menu 的类,有 3 个属性(不包括 sql id), 带有名称的字符串 带有价格的浮动 和成分清单
我可以在 MVC 视图中获取并添加/编辑名称和价格,没问题...但我的问题从列表开始...您如何添加它?我已经搜索了两天了,但找不到答案...我可能在这个问题上使用了错误的关键字,尽管我不知道哪些是正确的。
如果这个问题侮辱了你的智商,我也想提前道歉......不用斥责我,已经做得足够了
我的问题从列表开始...您如何添加它?
好吧,根据您的场景和要求,为了在创建菜单时添加
Ingredients
列表,您应该在配料索引上执行循环。
添加新成分时,您应该有一个带有 html Id 属性的表格。因此,在按钮单击事件上会有一个按钮,您应该在表内追加新的项目或行。最后与模型绑定并提交给控制器。
让我们看看如何实现这一目标。
型号:
public class Ingredient
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Menu
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public List<Ingredient> Ingredients { get; set; }
}
控制器:
public IActionResult Create()
{
return View(new Menu { Ingredients = new List<Ingredient>() });
}
查看:
@model Menu
@{
Layout = "_Layout";
int i = 0;
}
<h1>Create Menu</h1>
<form method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="Name" value="@Model.Name" class="form-control" />
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="number" id="price" name="Price" value="@Model.Price" class="form-control" />
</div>
<h2>Ingredients</h2>
<table id="ingredientsTable" class="table">
<thead>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach (var ingredient in Model.Ingredients)
{
<tr>
<td>
<input type="hidden" name="Ingredients[@i].Id" value="@ingredient.Id" />
<input type="text" name="Ingredients[@i].Name" value="@ingredient.Name" class="form-control" />
</td>
<td>
<button type="button" class="btn btn-danger removeIngredient" data-id="@ingredient.Id">Remove</button>
</td>
</tr>
i++;
}
<tr>
<td>
<input type="hidden" name="Ingredients[@i].Id" value="0" />
<input type="text" name="Ingredients[@i].Name" class="form-control" />
</td>
<td>
<button type="button" class="btn btn-danger removeIngredient">Remove</button>
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-primary addIngredient">Add Ingredient</button>
<input type="submit" value="Save" class="btn btn-success" />
</form>
@section Scripts {
<script>
$(document).ready(function () {
$(".addIngredient").click(function () {
var table = $("#ingredientsTable");
var row = "<tr><td><input type='hidden' name='Ingredients[new][@i].Id' value='0' />" +
"<input type='text' name='Ingredients[new][@i].Name' class='form-control' /></td><td><button type='button' class='btn btn-danger removeIngredient'>Remove</button></td></tr>";
table.find("tbody").append(row);
});
$(".removeIngredient").click(function () {
$(this).closest("tr").remove();
});
});
</script>
}
输出:
注意:这对您来说可能是一个良好的开始。如果您遇到任何问题,请发布一个新问题,其中包含足够的信息以及可重现的代码片段。