How to use multiple form elements in ASP.NET MVC

后端 未结 2 2034
刺人心
刺人心 2020-12-03 03:39

So I am new to ASP.NET MVC and I would like to create a view with a text box for each item in a collection. How do I do this, and how do I capture the information when it PO

2条回答
  •  清歌不尽
    2020-12-03 04:24

    You can do this:

    @for (int i = 0; i < Model.Guests.Count; i++) {
      @Html.TextBoxFor(m => m.Guests.ToList()[i].FirstName)
    }
    

    There are more examples and details on this post by Haacked.

    UPDATE: The controller post action should look like this:

    [HttpPost]
    public ActionResult Index(Room room)
    {
        return View();
    }
    

    In this example I'm considering that you have a Room class like this:

    public class Room
    {
        public List Guests { get; set; }
    }
    

    That's all, on the post action, you should have the Guests list correctly populated.

提交回复
热议问题