猿问

如何使用 Javascript 将下拉列表添加到 MVC 中的动态行并将值绑定到模型

我想在 javascript 中创建的行中添加一个下拉列表,并将所选下拉项的 id 或文本与我的模型绑定。


这是表格:


  <table id="LineItems" class="table table-bordered fixed">

        <thead>               

            <tr>

                <th width="10%" class="text-center">

                    @Html.Label("Qty")

                </th>

                <th width="40%" class="text-center">

                    @Html.Label("Description")

                </th>

                <th width="15%" class="text-center">

                    @Html.Label("Project Number")

                </th>

                <th width="10%" class="text-center">

                    @Html.Label("Unit Cost")

                </th>

                @if (Model.CanCreateCustSignOff == true)

                {

                    <th width="10%" class="text-center">

                        @Html.Label("Custom Sign off")

                    </th>

                    <th width="20%" class="text-center">

                        @Html.Label("Approver")

                    </th>

                }

                <th width="10%" class="text-center">

                    @Html.Label("Action")

                </th>

            </tr>

        </thead>

        <tbody id="lineItems">

        </tbody>

    </table>


    <div>

        <input type="button" value="Add Line Item" class="btn btn-primary" onclick="addLineItem()" />

    </div>

查看模型 - 选择列表项由控制器填充,由文本 = 用户名和作为 Guid 的值组成。这些数据来自数据库,我不知道会添加多少用户。


public List<string> Approvers { get; set; }


public class LineItems

{

   public int Qty { get; set; }

   public string Description { get; set; }

   public decimal UnitCost { get; set; }

   public decimal LineItemCost { get; set; }

   public string ProjectNumber { get; set; }

   public bool CustSignOff { get; set; }

   public string ApproverId { get; set; }

   public Guid? ProjectId { get; set; }


 }

Javascript - 我已经能够使用下面的方法成功绑定使用我的模型创建的所有行的条目。


潇潇雨雨
浏览 192回答 1
1回答

杨魅力

我可以通过创建行然后将选项添加到 ID 来解决这个问题:&nbsp;approverList = JSON.parse('@Html.Raw(Json.Encode(@Model.Approvers))');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var ddlId = document.getElementById(ddlApproverId);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (index in approverList) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ddlId.options[ddlId.options.length] = new Option(approverList[index], index.value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答