2014-10-30 61 views
0

我使用@Html.DropDownListFor建立一个选择对象,看起来像这样一个下拉列表:MVC 4 .NET使用jQuery修改设定的选项

<select id="GroupCode" name="GroupCode" tabindex="4"><option value="">Select One</option> 

<option value="1">One thing</option> 

<option value="17">Another thing</option> 

<option value="7">A Third thing</option> 

</select> 

有来的时候,在别的变化页面,我想换出的选项,并像

<select id="GroupCode" name="GroupCode" tabindex="4"><option value="">Select One</option> 

<option value="21">A completely different list</option> 

<option value="17">A second item only</option> 

</select> 

然而,当我在视图中设置断点,并期待在$(“#GroupCode”)。HTML结束了,我看到类似这个:

$('#GroupCode').html 
function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(
    __proto__: 
function() { 
    [native code] 
} 

    arguments: null 
    caller: null 
    length: 1 
    prototype: {...} 

我期待看到类似上面的html的东西。

我关心的是,通过替换#GroupCode的html,我将失去@ Html.DropDownFor代码提供的内容。

底线:用这种方法替换下拉列表中的内容有什么好方法?

+1

添加括号! '$('#GroupCode')。html();' – 2014-10-30 21:03:05

+1

使用'$('#GroupCode')。empty()'并使用'$('#GroupCode')添加新选项。append $('').val('21').text('Another option'));' – 2014-10-30 21:06:17

+0

这个工作(谢谢!),虽然它不是答案的形式。 – 2014-10-31 13:33:56

回答

1

看到这个Working fiddle例如

HTML

<select id="GroupCode" name="GroupCode" tabindex="4"> 
    <option value="">Select One</option> 
    <option value="1">One thing</option> 
    <option value="17">Another thing</option> 
    <option value="7">A Third thing</option> 
</select> 
<button id="testBtn" type="button">replace list with items with ids (21, 7)</button> 

脚本:

$(function() { 
    $(document).on("click", "#testBtn", function() { 
     $('#GroupCode').empty().append(
     $('<option/>', { 
      value: "", 
      text: 'Select One' 
     }), 
     $('<option/>', { 
      value: "21", 
      text: "A completely different list" 
     }), 
     $('<option/>', { 
      value: "17", 
      text: "A second item only" 
     })); 
    }); 
});