MVC4 - 使用Json自动完成

时间:2013-04-03 07:54:38

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

我正在使用ASP.NET MVC4和Entity Framework开发一个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),但没有任何改变。有什么想法解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

您的代码不起作用的原因是您尝试将域模型发送到视图,该模型很可能在其对象图中包含循环引用,而不是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对象,因为您需要向视图发送一个字符串数组。