Asp.net剃刀文本框数组列表项 [英] Asp.net razor textbox array for list items
问题描述
我无法找到或弄清楚如何利用项目(纸杯蛋糕)的列表,并在剃刀与数量字段中显示它们。
正在发生的事情是,我没能得到的值列表中的每个蛋糕的数量。你可以做的文本框数组在剃刀?
查看
< DIV CLASS =表单组>
<标签>&蛋糕LT; /标签>
@foreach(在Model.CupcakeList VAR蛋糕)
{
@ Html.TextBox(CupcakeQuantities,cupcake.Id)@ cupcake.Name< BR />
}
< / DIV>
MODEL
公开名单<&蛋糕GT; CupcakeList {搞定;组; }
公开名单< INT> CupcakeQuantities {搞定;组; }
控制器
公众的ActionResult的Create()
{
VAR模型=新PartyBookingModel()
{
CupcakeList = db.Cupcakes.ToList(),
CupcakeQuantities =新的List< INT>()
}; 返回查看(模型);
}
CUPCAKE(实体)
公共类蛋糕
{
公众诠释标识{搞定;组; }
公共字符串名称{;组; }
公共小数PerDozen {搞定;组; }
}
您必须使用一个索引,而不是的foreach
为它工作。
@for(INT I = 0; I< Model.CupcakeList.Count;我++)
{
@ Html.TextBoxFor(X => Model.CupcakeQuantities [I])@ Model.CupcakeList [I] .Name点< BR />
}
这将创建顺序命名+将被重组回模型上回发数量的条目。
我意识到这可能看起来是为什么不工作的foreach?,而是用foreach没有到 TextBoxFor
足够的可用反射的信息(因为它仅仅是一个单个对象),而数组的索引是通过从 Model.CupcakeQuantities [I]
前pression反射提取。
接收控制器方法应该一样传递到视图的模型:
例如
[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屋!