使用带有对象列表的JQuery自动完成功能不会产生任何搜索结果

时间:2014-05-07 22:36:08

标签: jquery asp.net-mvc entity-framework autocomplete

在我的控制器中,我得到了一个品牌列表:

        private IEnumerable<Brand> GetBrands()
    {
        List<Brand> brandList = new List<Brand>();

        List<Brand> brands = Brand.GetList();
        brands = brands.OrderBy(b => b.BrandCode).ToList();

        return brands;
    }

然后我将该列表填入ViewBag的编辑视图中:

        [HttpGet]
        public ActionResult Edit(int id)
        {
         this.ViewBag.BrandList = this.GetBrands();
        }

在我的编辑视图中,我正在尝试实现自动完成功能:

    <script type="text/javascript">
    $(document).ready(function () {
        var brandList = @Html.Raw(new JavaScriptSerializer().Serialize(this.ViewBag.BrandList));
        $('#BrandCode').autocomplete({
            source: brandList,
            minLength: 3
        });

        console.log(brandList);
    });
</script>

从控制台日志记录中,我看到brandList是一个对象列表:

console log

但我无法在BrandCode领域获得匹配?我做错了什么?

autocomplete

修改: 这是品牌实体:

public class Brand : PersistantEntity
{
    private IBrandRepository repository;

    public int Id
    {
        get { return this.repository.Id; }
        set { this.repository.Id = value; }
    }

    public string BrandCode
    {
        get { return this.repository.BrandCode; }
        set { this.repository.BrandCode = value; }
    }

    protected override Repository.Abstract.IRepository Repository
    {
        get { return this.repository; }
        set { this.repository = value as IBrandRepository; }
    }

    public Brand()
    {
        this.repository = RepositoryFactory.CreateFromConfig<IBrandRepository>();
    }

    internal Brand(IBrandRepository repository)
    {
        this.repository = repository;
    }

}

1 个答案:

答案 0 :(得分:0)

我更改了GetBrands的定义以返回字符串列表(BrandCodes)而不是Brand对象。这解决了这个问题。这是新定义:

        private IEnumerable<string> GetBrands()
    {
        List<string> brandList = new List<string>();

        List<Brand> brands = Brand.GetList();
        brands = brands.OrderBy(b => b.BrandCode).ToList();

        foreach (var brand in brands)
        {
            brandList.Add(brand.BrandCode.ToString()); 
        }

        return brandList;
    }