从MVC模型属性设置使用JQuery的Select的选定值 [英] Setting selected value of a Select using JQuery from an MVC model property
问题描述
我正在使用Ajax填充下拉列表
I am am filling a dropdown using Ajax
$(document).ready(function() {
var ID = $("#ID").val();
fillDropdown(ID); //fills the dropdown via an $.ajax call
var anotherID = @Model.AnotherID;
//alert(anotherID);
$("#AnotherID").val(anotherID); //try to set the selected value
});
该下拉列表在页面中定义为:
The dropdown is defined in the page as:
@Html.DropDownListFor(x => x.AnotherID, Enumerable.Empty<SelectListItem>())
用于设置下拉菜单的选定值的行是: $(#AnotherID").val(anotherID);
The line to set the selected value of the dropdown is: $("#AnotherID").val(anotherID);
,仅当我取消注释上面的警报时,它才有效!
and it only works if I uncomment the alert just above!
有什么想法吗?
推荐答案
Ajax调用是异步的.您必须在Ajax调用完成之后设置选定的值.警报为您节省时间...这就是它与警报配合使用的原因.如果您使用的是jquery,请添加onsuccess回调并在该回调中设置选定的值.
Ajax calls are asynchronous . You have to set the selected value after the Ajax call completes. The alert is buying you time... That's why it works with the alert. If you are using jquery the add an onsuccess callback and set the selected value within the callback.
这篇关于从MVC模型属性设置使用JQuery的Select的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!