我想动态地将列表项添加到使用jQuery的MVC DropDownListFor。不幸的是,当我运行我的代码时没有任何反应我已经使用console.log来检查正在生成的HTML,它是。任何帮助,将不胜感激!使用jQuery将列表项添加到MVC DropDownList
这里是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>
+1 mcpDESIGNS答案。另外:我认为你需要在$(document).ready(function(){})块中包装formHelpers(),因为它也使用jQuery。 – Faust 2012-07-26 13:11:37