2012-07-26 58 views
0

我想动态地将列表项添加到使用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> 
+0

+1 mcpDESIGNS答案。另外:我认为你需要在$(document).ready(function(){})块中包装formHelpers(),因为它也使用jQuery。 – Faust 2012-07-26 13:11:37

回答

3

http://jsfiddle.net/enbF7/4/ - 更新的jsfiddle与你产生CSHTML,现在的工作。类'clrDropDown'拼写错误,它在生成的HTML中拼写为'crlDropDown'。

的问题是你的$。每()函数中...

看起来只是你如何格式化值&文成<option> 此外,我认为你的itemClass.append(<option>).val(val)) < - 你能在这里试图给在itemClass时的值,因此它为什么被打破

$.each(options, function(value, text) { 
     itemClass 
      .append($('<option>', { value : value}) 
      .text(text)); 
    }); 

检查出的jsfiddle看到它在行动,希望帮助!

+1

稍微缩短一点:.append($('

+0

@mcpDESIGNS我试过了你的代码,但它不起作用 我生成的CSHTML有一点不同,我会在上面发帖 – 2012-07-26 13:35:10

+0

我把代码粘贴在小提琴中,为什么它不能在我的项目中工作?这是链接[My Fiddle](http://jsfiddle.net/singularity/uWUFL/)@mcpDESIGNS – 2012-07-26 13:50:08

0

虽然由mcpDESIGNS发布的作品(+1),我认为他不希望已经有select

我更新了他的小提琴与一个新的修订版,没有添加一个已经存在的列表与prepopulated值相同。

http://jsfiddle.net/enbF7/2/

+0

那没有用,我把我生成的CSHTML放在@DrColossos上面 – 2012-07-26 13:44:12