我正在尝试使用 jQuery 将列表项动态附加到 MVC DropDownListFor。不幸的是,当我运行我的代码时没有任何反应。我使用了 console.log 来仔细检查正在生成的 html,确实如此。任何帮助,将不胜感激!
这是 jQuery
function formHelpers() {
jQuery.fn.addDropDownValues = function (options) {
// Grab the class selector given to the function
var itemClass = $(this);
// Iterate through each element and value
$.each(options, function (val, text) {
itemClass.append("<option></option>").val(val).html(text);
});
};
};
$(document).ready(function () {
formHelpers();
$(".clrDropDown").addDropDownValues({Val1:"Yes", Val2:"No"});
});
这是cshtml
<div style="float:left;margin:0 10px 0 0;">
<table class="ntiTable">
<tbody>
<td nowrap class="ntiTableFirstColumn" title="This is the Crl Collaboration field."><div class="editor-label">@Html.LabelFor(m => m.myProject.CrlCollaboration)</div></td>
<td><div class="editor-field">@Html.DropDownListFor(model => model.myProject.CrlCollaboration, new SelectList(""), new { @class = "crlDropDown"})@Html.ValidationMessageFor(model => model.myProject.CrlCollaboration)</div></td>
</tbody>
</table>
</div>
生成的 CSHTML
<tr>
<td class="ntiTableFirstColumn" title="This is the Crl Collaboration field." nowrap="nowrap"><div class="editor-label"><label for="myProject_CrlCollaboration">Crl Collaboration</label></div></td>
<td><div class="editor-field"><select class="crlDropDown" data-val="true" data-val-length="The field Crl Collaboration must be a string with a maximum length of 10." data-val-length-max="10" id="myProject_CrlCollaboration" name="myProject.CrlCollaboration"></select><span class="field-validation-valid" data-valmsg-for="myProject.CrlCollaboration" data-valmsg-replace="true"></span></div></td>
</tr>