【问题标题】:MVC4 - AutoComplete using JsonMVC4 - 使用 Json 自动完成
【发布时间】:2013-04-03 07:54:38
【问题描述】:

我正在使用 ASP.NET MVC4 和实体框架开发 Intranet Web 应用程序。根据我的一个观点,我有一份未来可能会很庞大的人名单。因此,为了让事情变得更简单,我想使用 jQuery UI 和 Json 实现一个自动完成字段组件。

问题是当我使用我的数据库为我的 jQuery 代码提供源时,它不起作用。但是,当我通过硬编码数据创建变量时,它可以工作。

我的行动:

public ActionResult AutoComplete(string term)
{
    BuSIMaterial.Models.BuSIMaterialEntities db = new Models.BuSIMaterialEntities();

    //var result = new [] {"A","B","C","D","E","F"}; with this, it works

    var result = (from obj in db.Persons where obj.FirstName.ToLower().Contains(term.ToLower()) select obj).ToArray(); // with this, it doesn't work

    return Json(result, JsonRequestBehavior.AllowGet);
}

我的观点:

@{
    ViewBag.Title = "Auto";
}

<h2>Auto</h2>
<label for="persons">Persons : </label><input type="text" id="persons" name="persons"/>

@section Scripts
{
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/themes/base/css")

    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $('#persons').autocomplete({
                source: '@Url.Action("AutoComplete")'
            });
        });
    </script>
}

我尝试修改我的返回类型(JsonResult 而不是 ActionResult),但没有任何变化。有办法解决这个问题吗?

【问题讨论】:

  • 您能否详细说明“不起作用”。例如,您的结果数组是否有任何值?
  • 当我使用调试器时,我的结果变量中确实有值。我不知道为什么,但是当我使用我的数据库时自动建议不起作用。

标签: c# jquery asp.net-mvc json jquery-ui


【解决方案1】:

您的代码不起作用的原因是因为您试图将域模型发送到视图,该视图很可能在其对象图中包含循环引用并且不是 JSON 可序列化的。要解决此问题,请执行以下操作:

public ActionResult AutoComplete(string term)
{
    BuSIMaterial.Models.BuSIMaterialEntities db = new Models.BuSIMaterialEntities();

    //var result = new [] {"A","B","C","D","E","F"}; with this, it works

    var result = db
        .Persons
        .Where(p => p.FirstName.ToLower().Contains(term.ToLower()))
        .Select(p => p.FirstName) // <!-- That's the important bit you were missing
        .ToList();

    return Json(result, JsonRequestBehavior.AllowGet);
}

请注意我是如何将 Person 实体投影到字符串的(仅采用其 FirstName)。在您的示例中,您直接获取了整个 Person 对象,这对自动完成插件没有意义,因为您需要将字符串数组发送到视图。

【讨论】:

  • 确实,它有效...我想知道为什么它不起作用,而您只是巧妙地解释了它。再次感谢你。最后一个问题:我有一个方法“FullName”,它结合了名字和姓氏,我想通过执行 p => p.FullName 来显示它。但是,Visual Studio 说:The specified type member 'FullName' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
  • 你可以先执行查询然后投影:.Where(p =&gt; p.FirstName.ToLower().Contains(term.ToLower())).ToList().Select(p =&gt; p.FullName).ToList().
猜你喜欢
  • 1970-01-01
  • 2017-08-14
  • 2014-09-30
  • 1970-01-01
  • 2018-01-18
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多