C# 使用jQuery填充SELECT值后设置该值
我正在尝试使用jQuery填充SELECT,并在填充后设置所需的值。 我正在使用ASP.NETMVC5 问题是没有设置值 这是我的密码:C# 使用jQuery填充SELECT值后设置该值,c#,javascript,jquery,asp.net-mvc,C#,Javascript,Jquery,Asp.net Mvc,我正在尝试使用jQuery填充SELECT,并在填充后设置所需的值。 我正在使用ASP.NETMVC5 问题是没有设置值 这是我的密码: $(document).ready(function () { //DropDownLists Initialization ListCategories(); //Populates the dropdownlist PreviousCategory(); //Sets DropDownList value to previous s
$(document).ready(function () {
//DropDownLists Initialization
ListCategories(); //Populates the dropdownlist
PreviousCategory(); //Sets DropDownList value to previous state (posted value)
});
function PreviousCategory() {
var previousCategory = $("#PreviousCategory").val();
if (previousCategory != null && previousCategory != '') {
$("#IdCategory").val(previousCategory);
}
}
$PreviousCategory是一个隐藏输入,它在使用下一个代码进行回发后在服务器端获取其值:
@if (ViewBag.Category!=null)
{
@Html.Hidden("PreviousCategory",(object)ViewBag.Category);
}
这两个函数分别工作,DropDownList可以完美地填充,但是没有设置值。
如果我从另一个事件(例如单击按钮)触发PreviousCategory,则该值将得到完美设置
我认为没有必要发布ListCategories代码,因为它运行良好,您可以假设它填充了dropdownlist,不过如果有人认为有必要,请告诉我,我会编辑该帖子
编辑:
以下是ListCategories代码:
function ListCategories(){
_idOrganigrama = $("#IdOrganigrama").val()
_idTipoPedido = $("#IdTipoPedido").val()
data = { idOrganigrama: _idOrganigrama, idTipoPedido: _idTipoPedido }
$.post("ListCategories/", data, function (categoryList) {
$("#IdCategoria").empty();
$(categoryList).each(function () {
$("<option />", {
val: this.Id,
text: this.Descripcion
}).appendTo($("#IdCategory"));
});
});
}
顺便说一句,$IdCategory是select。问题似乎出现在ListCategories中,您可能正在使用类似ajax的异步函数从服务器获取数据并填充select 因此,请使用这样一种基于回调的解决方案
$(document).ready(function () {
//DropDownLists Initialization
ListCategories(PreviousCategory); //Populates the dropdownlist
//Sets DropDownList value to previous state (posted value) after the values are loaded
});
function PreviousCategory() {
var previousCategory = $("#PreviousCategory").val();
if (previousCategory != null && previousCategory != '') {
$("#IdCategoria").val(previousCategory);
}
}
function ListCategories(callback) {
//your ajax request to populate the select
$.ajax({}).done(function () {
//populate the select
//then at the last call the callback method which will set the value
callback()
})
};
你能把ListCategories的内容贴出来吗?或者是idCategoria1的呈现HTML。添加调试并检查previousCategory中的previousCategory值。2.您是舒尔吗?类别列表中存在previousCategory?我的代码是西班牙语,所以我将其翻译成英语,我忘了将idCategory更改为idCategory,我现在编辑问题并发布您问我的代码。@Alexander我已经这样做了,previousCategory确实获得了一个值,而且..该值存在于类别列表中。好的,所以,在ListCategories中异步加载数据时,应该使用@Arun P Johny解决方案。