Select2 -- 占位符不显示

Select2 -- placeholder not displaying

我在 asp.net mvc 5 应用程序中使用 Select2 插件。根据 documentation

The placeholder option allows you to pass in a data object instead of just a string if you need more flexibility. The id of the data object should match the value of the placeholder option.

我已经完全做到了,但是占位符仍然没有出现。

代码:

model.Step6.Titles.Insert(0, new SelectListItem() { Text = "Select a Title", Value = "0", Selected = true });

@Html.DropDownListFor(model => model.Step6.Title, Model.Step6.Titles, new { id="teamtitle", @style = "width: 100%;"})

$("select").select2({
    allowClear: true,
    placeholder: {
        id: "0",
        placeholder: "Select an Title"
    }
})

谁能告诉我我做错了什么?

我认为占位符是一个字符串。不是对象 https://select2.github.io/examples.html#placeholders

$("select").select2({
    allowClear: true,
    placeholder:"Select an Title"

})

错误是placeholder: "Select an Title"。应该是-

$("select").select2({
    allowClear: true,
    placeholder: {
        id: "0",
        text: "Select an Title" //Should be text not placeholder
    }
})

https://select2.org/placeholders

我写在这里是因为我花了很多时间来找出我的代码中的错误。 我的占位符 object 也没有显示(而占位符 string 显示正确)。关键是空选项元素需要将值与占位符 id 相匹配。 我的意思是,如果你像下面这样放置第一个空选项:

<option></option>

它不会与声明为

的占位符匹配
placeholder : { id:'0', text:'Please select...'}

它不会显示任何内容。 相反,你应该写:

 <option value="0"></option>

注意如果使用 multi-select select2 似乎需要占位符作为对象。有关使用 yadcf 的一般示例,请参阅 https://codepen.io/louking/pen/BGMvRP?#(抱歉,额外的复杂性,但我相信 yadcf 将 select_type_options 直接传递给 select2)。 (以下摘录)

  {
    column_number:2,
    select_type: 'select2',
    filter_type: 'multi_select',
    select_type_options:
      {
        placeholder: {
          id: -1,
          text: 'pick col2'
        },
        width: '200px',
        allowClear: true,
      }
  },