0

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>
4

2 に答える 2

3

http://jsfiddle.net/enbF7/4/ - 生成された cshtml で jsFiddle を更新しました。現在は動作します。クラス「clrDropDown」の綴りが間違っていました。生成された HTML では「crlDropDown」と綴られています。

問題は $.each() 関数内にあります...

値とテキストをどのようにフォーマットしたかのように見え<option> ますitemClass.append(<option>).val(val))

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

jsfiddle をチェックして、動作を確認してください。

于 2012-07-26T13:04:18.870 に答える
0

mcpDESIGNS による投稿は機能しますが (+1)、彼は既に利用可能な を望んでいないと思いますselect

私は彼のフィドルを新しいリビジョンで更新しました。これは、値が事前に入力された既存のリストを追加せずに同じことを行います。

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

于 2012-07-26T13:12:53.323 に答える