我想知道是否有人可以帮助我。
我正在尝试为我的MVC应用程序创建一个搜索框,它使用图像而不是文本自动填充(根据用户的输入提出建议)。
该功能将检查用户的输入是否类似于名为“Word”的Entity Framework数据库表中的“Title”属性,然后返回它的“Imagepath”属性,该属性是图像的字符串路径。
然后,应在视图中使用此路径返回自动完成用户查询的相关图像列表。然后可以点击这些图像并链接到各自的页面。
类似于下面但没有文字和单独的框图像:
https://www.algolia.com/doc/assets/images/guides/search-ui/autocomplete-textarea-8-2565ba67.png
我正在努力解决这里的代码,因为我不熟悉Ajax和Javascript,我理解这是实现这一目标所必需的。
我的尝试概述如下:
public class Word
{
public int Id { get; set; }
public string Title { get; set; }
public string Imagepath { get; set; }
}
[HttpPost]
public JsonResult AutoComplete(string Prefix)
{
var words= _context.Words.ToList();
var specifiedWords = (from w in words
where w.Title.StartsWith(Prefix) || w.Title.Contains(Prefix)
select new { w.Imagepath });
return Json(specifiedWords , JsonRequestBehavior.AllowGet);
}
<script src="~/Scripts/jquery-3.2.1.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<link rel= "stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" >
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#Title").autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Words/AutoComplete",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Imagepath,
value: item.Title
};
}));
}
});
},
open: (event) => {
$('.ui-autocomplete .ui-menu-item div').toArray().forEach((element) => {
let imagePath = element.innerHTML;
$(element).html('');
var inner_html = '<div class="list_item_container"><div class="image"><img src="' +
imagePath + '"></div>';
$(element).append(inner_html);
});
}
});
});
</script>
搜索框:
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
CSS:
<style>
.list_item_container {
width: 300px;
height: 60px;
padding: 5px 0;
}
.image {
width: 60px;
height: 60px;
margin-right: 10px;
float: left;
}
不用说,我最好的尝试还没有奏效。
JavaScript已经从这里的教程中大量使用(仅包含自动完成的单词:
任何有用资源的指针或链接都将受到大力赞赏。谢谢!
{
source: function(request, response) {
$.ajax({
url: '@Url.Action("AutoComplete", "Words")',
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data)
{
response($.map(data, function (item)
{
return {
label: item.Imagepath,
value: item.Title
}
}));
}
});
},
open: (event) => {
$('.ui-autocomplete .ui-menu-item div').toArray().forEach((element) => {
let imagePath = element.innerHTML;
$(element).html('');
var inner_html = '<div class="list_item_container"><div class="image"><img src="' +
imagePath + '"></div>';
$(element).append(inner_html);
});
}
}
var specifiedWords = (from w in words
where w.Title.StartsWith(Prefix) || w.Title.Contains(Prefix)
select new { w.Imagepath, w.Title });
return Json(specifiedWords, JsonRequestBehavior.AllowGet);