使用Json从搜索方法

时间:2017-09-24 08:44:59

标签: c# jquery .net linq-to-entities asp.net-mvc-5

我有一个问题,我的问题是我无法使用我的模型使用我的模型,我需要这种方法进行自动完成搜索; 这是我的错误信息:

"发生了System.NotSupportedException异常HResult = 0x80131515 Message =实体类型或复杂类型' PizzaTn.Context.ViewModels'无法在LINQ to Entities查询中构建。 Source =过程调用树:

  public JsonResult GetSearchValue(string search)
    {
        PizzaTnContext db = new PizzaTnContext();
        List<VilleModels> allsearch = new List<VilleModels>();
        allsearch = db.Villes.Where(x => x.VilleName.Contains(search)).Select(x => new VilleModels
        {
            IdVille = x.IdVille,
            VilleName = x.VilleName
        }).ToList();
        return new JsonResult { Data = allsearch, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

这是我的HTML

 <script>
    $("#searchInput").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("GetSearchValue", "Home")',
                datatype: "json",
                data: {
                    search: $("#searchInput").val()
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.VilleName, value: item.VilleName };
                    }
                    )
                    );
                },
                error: function (xhr, status, error) {
                    alert("error");
                }

            });
        }
    });
</script>

1 个答案:

答案 0 :(得分:0)

解决方案是添加一个参数.AsEnumerable()..感谢George:

db.Villes.Where(x => x.VilleName.Contains(search)).AsEnumerable().Select(x => new VilleModels { IdVille = x.IdVille, VilleName = x.VilleName }).ToList();