我已通过以下方式在MVC表单上声明了select2下拉列表:
@Html.DropDownListFor(m => m.ContactGroup.Id, Model.ContactGroupSelectList, "Select a Contact Group")
这会按预期填充并显示初始值。在另一个下拉列表的更改事件中,我想将上面的内容设置回默认值(默认情况下,我的意思是占位符值"选择联系人组"所以它是' s不属于实际数据)。如果我执行以下任一操作,则会将值设置回空字符串(空白)。我已经浏览了整个互联网,但没有找到解决方案:$('#ContactGroup_Id').select2("val", "Select a Contact Group");
$('#ContactGroup_Id').select2("val", "0");
答案 0 :(得分:0)
控制器操作:
public ActionResult Shop()
{
var fruits = new List<object>();
var vegetables = new List<object>();
fruits.Add(new { ID = 0, Name = "Banana" });
fruits.Add(new { ID = 1, Name = "Mango" });
vegetables.Add(new { ID = 0, Name = "Spinach" });
vegetables.Add(new { ID = 1, Name = "Potatoes" });
ViewBag.Fruits = new SelectList(fruits, "ID", "Name");
ViewBag.Vegetables = new SelectList(vegetables, "ID", "Name");
return View();
}
查看:强>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
$("#Vegetables").change(function () {
//When a value is changed in the Vegetables drop down set the Fruits dropdown to "Select a fruit"
$("#Fruits").val($("#Fruits option:first").val());
});
});
</script>
@Html.DropDownList("Fruits", ViewBag.Fruits as SelectList, "Select a fruit")
@Html.DropDownList("Vegetables", ViewBag.Vegetables as SelectList)
答案 1 :(得分:0)
以下内容将第一个(null
)选项设置为选中
$('#ContactGroup_Id').select2("val", "", "placeholder", "Select a Contact Group");
答案 2 :(得分:0)
$("#select2List").val("");
$("#select2List").select2().select2("val", "", "placeholder", "--select--");
答案 3 :(得分:-1)
假设您希望默认值为0,在javascript中尝试:
$('#ContactGroup_Id').val('0');
如果不起作用则回复