我正在尝试设置select2选项的默认选择值,但它不起作用...有人可以帮助我吗??
这是我的控制器
public ActionResult OrderAcceptanceDetails()
{
var res = Db.CustomerDetails.ToList();
Session["cust"] = new SelectList(res, "CUSTCODE", "CUSTCODE");
var yearlist = Db.Years.ToList();
Session["year"] = new SelectList(yearlist, "Year1", "Year1");
//var spresult = Db.Database.SqlQuery<OADetail>("Sp_OADetails_GetAll").ToList<OADetail>();
return View();
}
这是我的看法
<div class="col-md-3">
<p>
@Html.DropDownList("Year", Session["year"] as SelectList, "-- Select Year-- ", htmlAttributes: new { @class = "selectpicker", data_style = "select-with-transition" })
</p>
</div>
这是我的JavaScript
<script type="text/javascript">
$(document).ready(function () {
$("#Year").children("option:last-child").attr("selected",trues);
})
</script>
我要选择来自数据库的下拉值的最后一个子项。请告诉我这怎么可能??
答案 0 :(得分:1)
为此尝试使用Trigger属性: doc
$(document).ready(function () {
$("#Year").select2({ width: '75px' });
$("#Year").children("option:last-child").attr("selected", true).trigger('change');
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
<select id="Year">
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
</select>