使用jquery Ajax post方法我调用我的action方法,从数据库中提取记录并在下拉列表中显示它们。一切都很好。但我想在下拉列表中显示“请选择”作为第一个选项。我尝试了一切,但没有任何东西对我有利。任何帮助将非常感谢。以下是我的代码:
.cshtml:
<select id="ddlChannelGroupType" name="ddlChannelGroupType">
</select>
jquery ajax调用从数据库中获取记录:
$(document).ready(function () {
var funcareakey = @ViewBag.UserFuncAreaKey
$.ajax(
{
type: "POST",
url: "/MappingChannelGroup/GetCHGRPTYPE/",
data: {
userFunctionalAreaKey: funcareakey
},
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value='" + item.channelgrptypekey + "'>" + (item.channelgrptype) + "</option>";
});
$("#ddlChannelGroupType").html(items);
}
});
});
Controller上的我的Action方法:
public JsonResult GetCHGRPTYPE(int userFunctionalAreaKey)
{
List<ChannelGrpTypeVM> objCHGRPMST = MappingChannelToGroupRepository.GetChannelGrpTypeByFuncArea(userFunctionalAreaKey);
return Json(objCHGRPMST);
}
我在存储库中的逻辑:
public static List<ChannelGrpTypeVM> GetChannelGrpTypeByFuncArea(decimal funcareakey)
{
BarcDataContext bc = new BarcDataContext();
var query =
(from CHM in bc.XREF_CH_GRP_MST
join CGT in bc.REF_CH_GRP_TYPE on CHM.CH_GRP_TYPE_KEY equals CGT.CH_GRP_TYPE_KEY
where CHM.SRC_FUNC_KEY == funcareakey
select new ChannelGrpTypeVM
{
channelgrptype = CGT.CH_GRP,
channelgrptypekey = CGT.CH_GRP_TYPE_KEY
}).Distinct().OrderBy(m => m.channelgrptype).ToList();
return query;
}
答案 0 :(得分:2)
只需更改你的js:
// this line
items += "<option selected='selected' value=''>Please select</option>";
$.each(data, function (i, item) {
items += "<option value='" + item.channelgrptypekey + "'>" + (item.channelgrptype) + "</option>";
});
$("#ddlChannelGroupType").html(items);
答案 1 :(得分:2)
在$ .each
之前添加默认值success: function (data) {
var items = "";
items += "<option value='' disabled selected>Please select</option>";
$.each(data, function (i, item) {
items += "<option value='" + item.channelgrptypekey + "'>" + (item.channelgrptype) + "</option>";
});
$("#ddlChannelGroupType").html(items);
}
答案 2 :(得分:0)
尝试添加非显示选项并使用JS(或默认属性)选择它。
<select default='some-id' id="ddlChannelGroupType" name="ddlChannelGroupType">
<option value='some-id' className='display-none'>Please Select</option>
{ another options }
</select>