我的剃刀视图中有以下jQuery代码: -
$.each(CSData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
填充下拉列表的。但我如何检查当前itemData.Value是否等于某个Model值,如果是,则选择其值。诸如此类的东西: -
if(itemData.Value == @Model.ID).attr('selected', true);
由于
答案 0 :(得分:1)
创建后尝试设置选择的值:
$.each(CSData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
select.val('@Model.ID');
答案 1 :(得分:1)
您可以在下拉列表绑定后执行此操作,
if(itemData.Value == @Model.ID)
{
$("#dropdownID option[value='" + itemData.value +"']").attr("selected","selected"); // .prop('selected','selected')
}
这样你的功能应如下所示:
$.each(CSData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
if(itemData.Value == @Model.ID)
{
$("#dropdownID option[value='" + itemData.Value +"']").attr("selected","selected"); // .prop('selected','selected')
}
});
答案 2 :(得分:1)
怎么样:
if(itemData.Value == @Html.Raw(Model.ID)).attr('selected', true);
或根据需要在其周围加上引号:
if(itemData.Value == @Html.Raw("'" + Model.ID + "'")).attr('selected', true);
答案 3 :(得分:0)
// let's assume the following data
var CSData = {
"itemA": "foo a",
"itemB": "foo b",
"itemC": "foo c"
};
// let's assume this as the select element
var select = $("#fooData");
// let's append the CSData to the select
$.each(CSData, function (index, itemData) {
// first solve how you append the select element
select
.append($("<option></option>")
.attr("value", index)
.text(itemData));
if(itemData.Value == @Model.ID){
// matched, do whatever here
}
});