我想動態地將列表項添加到使用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