我正在尝试使用jQuery动态添加DropDownList助手
我编写的这段代码根据需要成功创建了下拉列表,但是代码以意想不到的格式呈现HTML标记,其中它为每个属性放置双引号'值!! (例如姓名="" HousingUnitCount"")
<select class=""form-control" input-sm"="" id=""HousingUnitCount"" name=""HousingUnitCount""><option value="""">Choose the number of housing Unit</option>
<option value=""0"">0</option>
<option value=""1"">1</option>
<option value=""2"">2</option>
<option value=""3"">3</option>
<option value=""4"">4</option>
<option value=""5"">5</option>
</select>
以下是我的代码,
这里我为我的列表定义全局变量,并在jQuery中使用HTML Helper
@{
ViewBag.Title = "TestingDynamicFormWithjQuery";
var unitsCountList = new List<SelectListItem> { new SelectListItem() {Text="0", Value="0"},
new SelectListItem() {Text="1", Value="1"},
new SelectListItem() {Text="2", Value="2"},
new SelectListItem() {Text="3", Value="3"},
new SelectListItem() {Text="4", Value="4"},
new SelectListItem() {Text="5", Value="5"}
};
var housingUnit = Html.DropDownList("HousingUnitCount", unitsCountList, "Choose the number of housing Unit", htmlAttributes: new { @class = "form-control input-sm" }).ToHtmlString();
}
这是我正在使用的HTML
<button id="addUnitBtn" type="button" name="addUnitBtn" class="btn btn-primary">
<span class="glyphicon glyphicon-plus-sign"></span> Add Unit
</button>
@using(Html.BeginForm())
{
<div id="addUnitDiv">
</div>
<br/><br /><br />
<input id="Submit" type="submit" value="Save" class="btn btn-primary btn-lg" />
}
下面是动态添加DropDownList的jQuery代码
@section Scripts{
<script type="text/javascript">
$(window).ready(function () {
console.log('windows ready');
$('button[name="addUnitBtn"]').on("click", function () {
console.log('btn clicked');
$("#addUnitDiv").append('<div>@Ajax.JavaScriptStringEncode(housingUnit)</div>');
});
});
</script>
}
答案 0 :(得分:2)
这个怎么样
<script type="text/html" id="template">
<div class="template-wrapper">
@Html.DropDownList("HousingUnitCount", unitsCountList, "Choose the number of housing Unit", htmlAttributes: new { @class = "form-control input-sm"})
</div>
</script>
然后在你的javascript代码中:
@section Scripts{
<script type="text/javascript">
$(window).ready(function () {
console.log('windows ready');
$('button[name="addUnitBtn"]').on("click", function () {
console.log('btn clicked');
var $template = $.trim($($('#template').html()));
updateTemplateElementsNameAttr($template);
$("#addUnitDiv").append($template);
});
});
function updateTemplateElementsNameAttr($template){
var nextIndex = $('.template-wrapper').length;
$template.find('select').each(function(){
var nameAttr = $(this).attr('name') + '[' + nextIndex + ']';
$(this).attr('name', nameAttr);
}
}
</script>
}