用于列表项的 Asp.net 剃刀文本框数组 [英] Asp.net razor textbox array for list items
问题描述
我无法找到或弄清楚如何获取项目列表(纸杯蛋糕)并将它们显示在带有数量字段的剃刀中.
发生的事情是我无法获取列表中每个纸杯蛋糕数量的值.你可以在 Razor 中做文本框数组吗?
查看
<label>纸杯蛋糕</label>@foreach(Model.CupcakeList 中的 var cupcake){@Html.TextBox("CupcakeQuantities", cupcake.Id) @cupcake.Name
}
模型
公共列表CupcakeList { 得到;放;}公共列表纸杯蛋糕数量 { 得到;放;}
控制器
public ActionResult Create(){var 模型 = new PartyBookingModel(){CupcakeList = db.Cupcakes.ToList(),CupcakeQuantities = new List()};返回视图(模型);}
纸杯蛋糕(实体)
公共类纸杯蛋糕{公共 int Id { 获取;放;}公共字符串名称 { 获取;放;}公共十进制 PerDozen { 得到;放;}}
您必须使用索引,而不是 foreach
才能使其工作.
@for (int i = 0; i Model.CupcakeQuantities[i]) @Model.CupcakeList[i].Name <br/>}
这将创建按顺序命名+编号的条目,这些条目将在回发时重新组合回模型中.
我意识到这看起来像是为什么 foreach 不起作用?",但是对于 foreach
,TextBoxFor
没有足够的反射信息(因为它只是单个对象),而数组索引是通过反射从 Model.CupcakeQuantities[i]
表达式中提取的.
接收控制器方法应该与传递给视图的模型相同:
例如
[HttpPost]公共 ActionResult(PartyBookingModel 模型)
I can't find or figure out how to take a list of items (cupcakes) and display them in razor with a quantity field.
What is happening is I am not able to get the values for each cupcake quantity in the list. Can you do textbox arrays in Razor?
VIEW
<div class="form-group">
<label>Cupcakes</label>
@foreach (var cupcake in Model.CupcakeList)
{
@Html.TextBox("CupcakeQuantities", cupcake.Id) @cupcake.Name <br/>
}
</div>
MODEL
public List<Cupcake> CupcakeList { get; set; }
public List<int> CupcakeQuantities { get; set; }
CONTROLLER
public ActionResult Create()
{
var model = new PartyBookingModel()
{
CupcakeList = db.Cupcakes.ToList(),
CupcakeQuantities = new List<int>()
};
return View(model);
}
CUPCAKE (ENTITY)
public class Cupcake
{
public int Id { get; set; }
public string Name { get; set; }
public decimal PerDozen { get; set; }
}
You have to use an index, rather than foreach
for it to work.
@for (int i = 0; i < Model.CupcakeList.Count; i++)
{
@Html.TextBoxFor(x=>Model.CupcakeQuantities[i]) @Model.CupcakeList[i].Name <br/>
}
This will create sequentially named+number entries that will be recombined back into the model on post back.
I realise this may seem like "why doesn't foreach work?", but with foreach
there is not enough reflected information available to TextBoxFor
(as it is just a single object), whereas the array index is extracted by reflection from the Model.CupcakeQuantities[i]
expression.
The receiving controller method should take the same as the model passed to the view:
e.g.
[HttpPost]
public ActionResult(PartyBookingModel model)
这篇关于用于列表项的 Asp.net 剃刀文本框数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!