【发布时间】:2017-08-21 04:45:33
【问题描述】:
我在 asp.net 核心工作。我正在使用打字稿。我想使用 Select2。如何在 asp.net core 中使用 select2?有没有要安装使用 select2 的包?
【问题讨论】:
标签: c# typescript asp.net-core jquery-select2
我在 asp.net 核心工作。我正在使用打字稿。我想使用 Select2。如何在 asp.net core 中使用 select2?有没有要安装使用 select2 的包?
【问题讨论】:
标签: c# typescript asp.net-core jquery-select2
聚会迟到了,但遇到了同样的问题。
我需要添加一个 select2-multiselector,其中数据是通过 ajax 加载的。所以可能你需要改变一下。
你可以添加这个js和css:
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/js/select2.min.js"></script>
我的观点(模型是IEnumerable):
...
@for (int index = 0; index < Model.Count; index++)
{
<div>
<input type="hidden" asp-for="@Model[index].Id"/>
<input type="text" asp-for="@Model[index].Title">
<select class="js-example-basic-multiple" style="width: 100%;" asp-for="@Model[index].TagIds" multiple="multiple">
@foreach (TagDetailModel tag in Model[index].Tags)
{
<option value="@tag.Id" selected="selected">@tag.Name</option>
}
</select>
</div>
}
...
我做了什么:
在视图中添加了select,给了它一个类,以后我可以使用 javascript 访问它。如果需要添加多个值,则添加multiple="multiple"
在我的模型中,我添加了已经分配给模型的标签。 select2不会自动添加它们,您需要自己添加它们。如果您没有启用多个,那么您的Tags 可能只是一个Tag,您无需枚举。
$(document).ready(function() {
$('.js-example-basic-multiple').select2({
ajax: {
url: '/Tag/GetTags',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
}
}
});
});
在此脚本中,当文档完全加载后,我将select 运行为select2,只使用$('.js-example-basic-multiple').select2()。我想让 select2 通过 ajax 加载选项(因此是 ajax 属性) - 如果您不想使用 ajax,您可以在视图中添加可能的值,例如 <option value="@tag.Id">@tag.Name</option>。
在我的控制器中(ImageController.cs 在我的应用程序中)我刚刚为 ajax-request 添加了一个函数:
public async Task<JsonResult> Tags(int id)
{
return Json(await _imageService.Get(id));
}
【讨论】: