我尝试制作一个文本框,为MVC文本框中的用户名自动完成提供建议。自动完成部分有效,但我似乎无法将其添加到句子而不是完全替换它!
我对Jquery / javascript不太满意,所以我试图在C#中尽我所能,但我想我现在正处于道路尽头......我在这里找到一个示例之后使用jquery-ui-1.11自动完成功能:Autocomplete tutorial
这是Jquery自动完成脚本:
$(".newpostbox").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
async: false,
cache: false,
type: "POST",
url: "@(Url.Action("Autocomplete", "Home"))",
data: { "term": request.term },
minLength: 2,
success: function (data) {
for (var i = 0; i < data.length ; i++) {
customer[i] = { label: data[i].Second, Id: data[i].First};
}
}
});
response(customer);
}
});
我以为我很聪明地使用Triplet来发送值/ id,所以我实际上有了所需的&#34;句子的第一部分&#34;在数据[i]。第三。很近!
我不知道看到控制器是否重要,但无论如何我都会发布它:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Autocomplete(string term) {
//split string
string[] dividers = { " ", ".", ",", "!", "?", "\n", "\r\n" };
string[] splits = term.Split(dividers, StringSplitOptions.RemoveEmptyEntries);
int index = splits.Length - 1;
//look for @ signs
if(index >= 0 && splits[index].Length > 1 && splits[index][0] == '@') {
string impoterm = splits[splits.Length - 1].Substring(1);
int end = term.Length - 1;
do {
end--;
} while(end >= 0 && term[end] != '@');
string beginning = term.Substring(0, end);
//get names from DB
StaticTagsContext tagdb = new StaticTagsContext();
var tags = from a in tagdb.StaticTags where a.Name.Contains(impoterm) select a;
List<StaticTag> taglist = tags.ToList();
var names = new List<Triplet>();
//IMPORTANT PART I GUESS
for(int i = 0; i < taglist.Count(); i++) {
names.Add(new Triplet(
i.ToString(), //First: ID
"@" + taglist[i].Name, //Second: DisplayName
//Third: Full sentence that I want in textbox
beginning + "@" + taglist[i].Name));
}
return Json(names.ToList(), JsonRequestBehavior.AllowGet);
}
return Json(null);
}
TL; DR:有没有办法将下拉框中显示的内容与选择时文本框中放置的内容分开,使用Jquery自动完成?