Asp.net razor textbox array for list items

天大地大妈咪最大 提交于 2019-11-29 09:43:50

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)

Try it this way:

view:

@for (int i = 0; i < Model.Count; i++)
{
    @Html.HiddenFor(x=>Model[i].Id) @Model[i].Name  
    @Html.TextBoxFor(x => Model[i].Quantity) <br/>
}

model:

public class CupcakeViewModel
{
   public int Id {get;set;}
   public string Name {get;set;}
   public int Quantity {get;set;}   
}

controller:

public ActionResult Create()
{
    var model = db.Cupcakes.Select(c => new CupcakeViewModel {
                                                Id = c.Id,
                                                Name = c.Name,
                                                Quantity = 0 
                           })
                           .ToList();

    return View(model);
}

[HttpPost]
public ActionResult Create(CupcakeViewModel[] cakes)
{
     //Save choosen cakes
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!