无法在 .NET Core Web 应用程序中发布 IEnumerable 数据

问题描述 投票:0回答:1

我有一个 C# .NET Core Web 应用程序(不是 MVC Web 应用程序)。我正在尝试发布

IEnumerable
集合中的数据。对于这篇文章,我简化了它:

在 CS 文件中:

[BindProperty]
public IEnumerable<NpcpAllFields> NpcpAllFields { get; set; }

在 CSHTML 文件中:

<form asp-page-handler="SaveData" method="post">
    <button type="submit" class="btn btn-primary" id="checkBtn" formmethod="post">Submit</button><br />
    <table class="table">
        <tr>
            <th>
                Sales Order Number
            </th>
            <th>
                Sales Order Line
            </th>
            <th>
                Is NPC
            </th>
        </tr>
        @foreach (var i in Model.NpcpAllFields)
        {
            <tr>
                <td>
                    <input class="form-control" name="@i" asp-for="@i.SALES_ORD_NO"  />
                </td>
                <td>
                    <input class="form-control" name="@i" asp-for="@i.SALES_ORD_LN_NO"  />
                </td>
                <td>
                    <input class="form-control" name="@i" asp-for="@i.IS_A_NEW_PART"  />
                </td>
            </tr>
        }
    </table>
</form>

有问题的主要代码是

foreach

@foreach (var i in Model.NpcpAllFields)
{
    <tr>
        <td>
            <input class="form-control" name="@i" asp-for="@i.SALES_ORD_NO"  />
        </td>
        <td>
            <input class="form-control" name="@i" asp-for="@i.SALES_ORD_LN_NO"  />
        </td>
        <td>
            <input class="form-control" name="@i" asp-for="@i.IS_A_NEW_PART"  />
        </td>
    </tr>
}

上面完美地显示了数据。但是当我提交数据并检查调试器中的

NpcpAllFields
集合时,它是空的。问题可能是
name
字段中的值(我尝试了很多不同的方法):

name="@i" 

我能够将集合放入

for
循环(而不是
foreach
)中,并且它确实填充了调试器中的字段,但它无法正确显示,运行缓慢,并且数据不正确。

我意识到有类似的帖子与此相关,但我找不到能解决我的问题的帖子。许多帖子/答案都是针对 .NET Core MVC 应用程序。

c# asp.net-core razor-pages ienumerable
1个回答
1
投票

您为

name
属性提供了错误的值。因此,提交表单时,
NpcpAllFields
不与值绑定。检查
<input>
语句中的
@foreach
元素,您将看到这些元素呈现为:

<input class="form-control" name="<Namespace>.NpcpAllFields" />

@index
放在页面顶部(在
@model
之后)。

@{ int index = 0; }

渲染

name
属性如下:

@foreach (var i in Model.NpcpAllFields)
{
    <tr>
        <td>
            <input class="form-control" name="NpcpAllFields[@index].SALES_ORD_NO" asp-for="@i.SALES_ORD_NO"  />
        </td>
        <td>
            <input class="form-control" name="NpcpAllFields[@index].SALES_ORD_LN_NO" asp-for="@i.SALES_ORD_LN_NO"  />
        </td>
        <td>
            <input class="form-control" name="NpcpAllFields[@index].IS_A_NEW_PART" asp-for="@i.IS_A_NEW_PART"  />
        </td>
    </tr>

    index++;
}
© www.soinside.com 2019 - 2024. All rights reserved.