Diego Unanue
Diego Unanue

Reputation: 6826

MVC Send a list of objects

I've got an Index View with a table populated with data from a List property, but when I post the form with the table, the property is null.

Here is the Model:

public class BillViewModel
{

    public List<Product> ListProducts { get; set; }

}

Here is the product view:

    public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public decimal Price { get; set; }
}

Here is the View:

@using (Html.BeginForm())
{

<input type="submit" value="Aceptar"/>


<table id="tabla">


    @foreach (var item in Model.ListProducts)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ProductName)
            </td>
        </tr>
    }

</table>
}

I can add or delete Products, but how can i get the product list in the controller?:

    [HttpPost]
    public ActionResult Index(BillViewModel billViewModel)
    {


        return View();
    }

Upvotes: 2

Views: 4850

Answers (1)

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15148

That's quite easy, all you need to do is place all the item properties in the form, so something like:

<input type="submit" value="Aceptar"/>
<table id="tabla">
    @for (int i = 0; i < Model.ListProducts.Count; i++)
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x.ListProducts[i].ProductId)
                @Html.HiddenFor(x => x.ListProducts[i].Price)
                @Html.DisplayFor(x => x.ListProducts[i].ProductName)
            </td>
        </tr>
    }
</table>

Upvotes: 4

Related Questions