首页 > 解决方案 > 将列表中每一项的值提交给控制器(MVC)

问题描述

我正在尝试制作某种购物车,因此我在视图中显示了一个项目列表。

我添加了一个带有“+ Add”值的提交按钮和一个带有显示的每个项目的值金额的数字输入。

这是我的代码:

看法:

@model MyProject.ViewModel.AddProductsViewModel

@{
    Layout = null;
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<table class="table" align="left" style="padding-left:15px">
    <tr>
        <th>
            Product
        </th>
    </tr>

    @foreach (var item in Model.ProductsList)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Descripcion)
            </td>
            <td>
                <input type="hidden" name="ProductId" value="@item.ProductId" />                                                                       
                <input type="number" id="Amount" name="Amount"
                       min="1" max="30" value="1">
                <input type="submit" value="+ Add" class="btn btn-primary" />
            </td>
        </tr>
    }
</table>
}

型号类:

public class AddProductsViewModel
{
    ...stuff here...
          
    public List<Products> ProductsList { get; set; }
}

我需要我的控制器productId从我单击提交到的项目中获取,但这样我只能获取列表中第一项的 Id。我怎样才能做到这一点?

标签: c#.netasp.net-mvc

解决方案


@{int i = 0;}
@foreach (var item in Model.ProductsList)
{

    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Descripcion)
        </td>
        <td>
            <input type="hidden" name="ProductsList[@i].ProductId" value="@item.ProductId" />                                                                       
            <input type="number" id="Amount" name="ProductsList[@i].Amount"
                   min="1" max="30" value="1">
            <input type="submit" value="+ Add" class="btn btn-primary" />
        </td>
    </tr>
     @(i++)
}

推荐阅读