Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

c# - Asp.net razor textbox array for list items

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; }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...