【问题标题】:Posting dynamically added html table rows to controller as parameter - ASP.NET Core/MVC将动态添加的 html 表行作为参数发布到控制器 - ASP.NET Core/MVC
【发布时间】:2021-01-24 20:25:22
【问题描述】:

在下面显示的表格中,动态创建了一行,我使用@Html.BeginForm 提交数据而不是 jQuery ajax。有没有更好的方法来做到这一点?

<table class="table table-bordered table-hover table-sortable" id="tab_logic">
    <thead>
        <tr>
            <th class="text-center">
                Degree / Diploma / Certificate
            </th>
            <th class="text-center">
                Name Of Board / University
            </th>
            <th class="text-center table-cell-label">
                Passing Year
            </th>
            <th class="text-center" style="border-top: 1px solid #ffffff; border-right: 1px solid #ffffff;">
            </th>
        </tr>
    </thead>
    <tbody>
        @{
            int i = 0;

            foreach (var item in Model.qualifications.ToList())
            {
                <tr class="hidden">
                    <td>
                        @Html.EditorFor(o => o.qualifications[i].AcedamicQualification, new { @id="AcedamicQualification" + i, @name = "AcedamicQualification", @class ="form-control" })
                    </td>
                    <td>
                        @Html.EditorFor(o => o.qualifications[i].Board, new { @id="Board" + i, @name = "Board", @class ="form-control" })
                    </td>
                    
                    <td>
                        <button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove'></button>
                    </td>
                </tr>
                i++;
            }
        }
    </tbody>
</table>

我试图绑定动态添加的行的模型

public class AdmissionFormViewModel
{
    public List<Qualification> qualifications { get; set; }
}

public class Qualification
{
    public string AcedamicQualification { get; set; }
    public string Board { get; set; }
    public string PassingYear { get; set; }
}

这是我的控制器

public IActionResult PostAdmission(AdmissionFormViewModel admissionFormViewModel)
{
    return View("/School/Form");
}

【问题讨论】:

    标签: javascript jquery asp.net-mvc asp.net-core model-view-controller


    【解决方案1】:

    form post不需要写js.ajax不需要刷新页面。你的actionPostAdmission表示你想在post之后重定向,并且你的视图代码已经绑定了模型,所以我认为form post是更好。

    如果你想传递整个模型,你只需要把表格放在一个表格中,如果你还想传递PassingYear给模型,你可以在foreach中使用下面的代码

       <input asp-for="@item.PassingYear" name="qualifications[i].PassingYear" hidden/>
    

    我找到了代码

    @id = "AcedamicQualification" + i, @name = "AcedamicQualification"
    @id="Board" + i, @name = "Board"
    

    没有改变id或name,可以移除。绑定模型时,name必须是qualifications[i].xxx

    如果你只想提交一行,可以把form放在foreach里面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多