如何从strongTyped模型填充动态添加的下拉列表

时间:2017-03-19 03:27:18

标签: javascript jquery asp.net-mvc razor model-binding

关于SO的很多问题都是关于使用Ajax数据来填充dropdownsList。

但是,我已经拥有包含SelectList项的强类型模型中的数据。我想用它来填充我的下拉列表 - 我该怎么做?

因此,在向具有下拉列表的表中添加新行之后,如何从数据填充/绑定新克隆的dropDownList cities Model

// List of cities in my Model, Location
LocationModel {
...
IEnumerable<City> Cities }

克隆行:在我的视图中我克隆了一行

<table id="rowtemplate">
 <tr>
   <td>
      <input type="hidden" name="Records.Index" value="#" />
        <span class="citiesCss">
          //DropDownList to clone
            <select class="form-control citiesCssId" id="Records_[#]__SelectedCityFromList" name="Records[#].SelectedCityFromList">
                <option value="">Default</option>                
            </select>
     </span>
   </td>

   <td> ... another cell       
  </td>
</tr>
</table>

如何从CityList model值绑定/填充新克隆的下拉列表

    $("#CloneButton").click(function () {
        var index = (new Random());
        var clone = $('#rowtemplate').clone();
        clone.html($(clone).html());
        clone.find('.cities').text(cities);            
        $('#MainTable').append(clone.find('tr'));
    });

1 个答案:

答案 0 :(得分:1)

您可以在生成视图时根据您的集合在模板中创建选项。假设City包含属性IdName,那么

<table id="rowtemplate">
    ....
    <select class="form-control citiesCssId" name="Records[#].SelectedCityFromList">
        <option value="">Default</option>
        @foreach(var city in Model.Cities)
        {
            <option value="@city.Id">@city.Name</option>
        }              
    </select>
    ....
</table>

现在,当您使用var clone = $('#rowtemplate').clone();复制模板时,clone的值还包含<option>元素