使用ASP.NET MVC Razor在JQuery中填充Html.DropDownList()

时间:2018-11-13 08:06:29

标签: c# jquery asp.net-mvc razor

我想在dropdownlist命中时在每一行中获得addrow button。 我不知道该怎么做。 这是我拥有的:

$('#addrow').click(function () {
  var tr = "<tr><td>@@Html.DropDownList(\"Bank\", null, htmlAttributes: new { @@class = \"form-control\" })"
  + "</td><td><div>"
  + "<div class=\"input-group date\">"
  + "<div class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i>"
  + "</div>"
  + "<input type=\"text\" class=\"form-control ChqDate\" name=\"ChqDate\" placeholder=\"Chq Date\">"
  + "</div><!-- /.input group -->"
  + "</div></td>"
  + "<td><input type=\"number\" name=\"Amount\" class=\"form-control\" id=\"ChqAmount\" placeholder=\"Cheque Amount\" /></td>"
  + "<td><button data-itemId=\"0\" type=\"button\" class=\"btn btn-danger removeRow\"><span class=\"glyphicon glyphicon-trash\"></span></button></td></tr>";

  $('#example1 tbody').append(tr);
  $('#example1 tbody .ChqDate').datepicker({
    autoclose: true
  });
});

1 个答案:

答案 0 :(得分:1)

首先在视图中显示下拉菜单(但用户看不见):

  @Html.DropDownList("Bank-Template", null, htmlAttributes: new { style="display: none;", id="Bank-Template" })

,然后在javascript中将其用作模板:

$('#addrow').click(function () {
    var tr = "<tr><td><select name=\"Bank\" class=\"form-control\">" + $("#Bank-Template").html()
    + "</select></td><td><div>"
    + "<div class=\"input-group date\">"
    + "<div class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i>"
    + "</div>"
    + "<input type=\"text\" class=\"form-control ChqDate\" name=\"ChqDate\" placeholder=\"Chq Date\">"
    + "</div><!-- /.input group -->"
    + "</div></td>"
    + "<td><input type=\"number\" name=\"Amount\" class=\"form-control\" id=\"ChqAmount\" placeholder=\"Cheque Amount\" /></td>"
    + "<td><button data-itemId=\"0\" type=\"button\" class=\"btn btn-danger removeRow\"><span class=\"glyphicon glyphicon-trash\"></span></button></td></tr>";

    $('#example1 tbody').append(tr);
    $('#example1 tbody .ChqDate').datepicker({
        autoclose: true
    });
});

,但是必须为控件设置唯一的名称,否则数据可能以数组形式发布到服务器。例如ChqDate [0],Bank [0],ChqDate [1],Bank [1],...