简体   繁体   中英

How to pass loop textbox to controller variable in ASP.NET MVC

I am passing a list from my controller to my view, and then inside a form I loop through each list item and display it with some textboxes that filled with value for each item. And then I want to submit every texboxes to controller, but it return null on it.

here is my model:

    public class DataRedpack
        {
            public string IdRedpack { get; set; }
            //and other properties...
        }

and here is my view:

    @model IEnumerable<SisFoPengelolaanPengirimanBarang.Models.DataRedpack>
    @using (Html.BeginForm("InsertRedpack", "Admin", FormMethod.Post))
    {
    
         foreach (var item in Model)
         {
              @Html.Hidden("IdRedpack", item.IdRedpack)
              @Html.TextBox("AmountPack", null, new { type = "number", @class = "form-control", @name = "AmountPack", @min=1, @max=50 })
         }
    }

it pass null to my controller:

    public ActionResult InsertRedpack(List<string> IdRedpack, List<int> AmountPack) //it returing null on this
            {
                if (IdRedpack.Any() && AmountPack.Any()) //and got exception on this
                {
                    //updating redpack with id and so on...
                }
            }

I need help how to figure this

Add "name" for each element in the loop like "IdRedpack[0]". replace an index variable with each loop. Also change your Controller Action method like.

public ActionResult InsertRedpack(IEnumerable<SisFoPengelolaanPengirimanBarang.Models.DataRedpack> model)
{
          //Validate your model here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM