gpt4 book ai didi

c# - 如何在 asp.net mvc 中使用标记在 Select2 输入中设置默认值

转载 作者:行者123 更新时间:2023-11-29 19:46:07 24 4
gpt4 key购买 nike

在我看来,我有这个 Select2 输入框充当标签 Controller :

CSHTML

<input id="tagSelector" type="hidden" style="width: 300px"/>

JS

  $('#tagSelector').select2({
placeholder: 'Select a tag...',
multiple: true,
ajax: {
url: '@Url.Action("SearchTags", "UnitDetails")',
dataType: 'json',
data: function(term, page) {
return {
searchTerm: term
};
},
results: function(data, page) {
return { results: data };
}
},
createSearchChoice: function(term) {
return { id: term, text: term };
}
}).on("removed", function(e) {
var url = '@Url.Content("~/UnitDetails/UnTagUnit/" + Model.ViewUnitContract.Id)';
var id = e.val;
var tagName = e.choice.text;
console.log(id + " : " + tagName);

$.ajax({
url: url,
data: { selectedItem: tagName },
type: 'GET',
dataType: 'json',
success: function() {
},
error: function() {
}
});
})
.on("select2-selecting", function(e) {
var url = '@Url.Content("~/UnitDetails/TagUnit/" + Model.ViewUnitContract.Id)';
var id = e.val;
var tagName = e.object.text;
console.log(id + " : " + tagName);

$.ajax({
url: url,
data: { selectedItem: tagName },
type: 'GET',
dataType: 'json',
success: function() {
},
error: function() {
}
});
});
});

C#

public JsonResult GetInitialTags(int id)
{
Model = new UnitDetailsModel(UnitClient.GetUnit(id));
foreach (var tag in Model.ViewUnitContract.Tags)
{
Model.TagsSelected.Add(tag);
}

var result = Model.TagsSelected.Select(a => new
{
id = a.Id,
text = a.Name
});

return Json(result, JsonRequestBehavior.AllowGet);
}

现在,我似乎不知道如何使用 initSelection 来用已经选择的标签填充输入框。我希望有人能帮我解决这个问题,因为我开始感到有点迷茫:)

最佳答案

通过将 initSelection 属性添加到我的 javascript 找到解决方案:

...
initSelection: function (element, callback) {
$.get('@Url.Action("GetInitialTags", "UnitDetails", new { id = Model.ViewUnitContract.Id })', function (initTags) {
var tags = [];

for (var i = 0; i < initTags.length; i++) {
tags.push({ "id": initTags[i].id, "text": initTags[i].text });
}

callback(tags);
});
},
...

关于c# - 如何在 asp.net mvc 中使用标记在 Select2 输入中设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19565470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com