簡體   English   中英

將 html 表行動態發布到 controller 作為參數 - ASP.NET Core/MVC

[英]Posting dynamically added html table rows to controller as parameter - ASP.NET Core/MVC

在下表中,一行是動態創建的,我使用@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>

Model 我試圖通過它綁定動態添加的行

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; }
}

這是我的 controller

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

form post不需要寫js.ajax不需要刷新頁面。你的Action PostAdmission表示你想在post后重定向,你的視圖代碼綁定了model,所以我覺得form post更好。

如果想傳整個model,只需要把表格放在表格里,如果還想傳PassingYear給model,可以在foreach中使用如下代碼

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

我找到了代碼

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

id 和 name 都沒有改,可以去掉。綁定 model 時,name 需要是qualifications[i].xxx

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM