【问题标题】:jQuery Autocomplete tied to WCF Service ASP.NET MVCjQuery 自动完成绑定到 WCF 服务 ASP.NET MVC
【发布时间】:2012-11-02 14:11:12
【问题描述】:

ASP.NET MVC 和编程的新手,我已经搜索了有关此主题的材料,但没有找到针对我的特定问题的具体答案。

我正在进行的项目需要使用 WCF 服务。最初,我从一个有效的 jQuery 自动完成功能开始,但是将代码移动到 WCF 服务中断了一些通信。自动完成功能不再起作用

WCF 服务

public IList<Location> QuickSearchLocation(string term)
    {
        using (var db = new InspectionEntities())
        {
            //return all locations except the reserved "Other"
            return db.Locations
                .Where(r => r.LocationName.Contains(term) && r.LocationId !=    Constants.OtherId)
                .ToList();
        }
    } 

上述代码旨在根据与子表的关系获取用户输入。如果用户输入与子表中的数据不匹配,则用户条目将保存到主数据库中的“其他”列。

控制器

public ActionResult QuickSearchLocation(string term)
    {
        return Json(_service.QuickSearchLocation(term), JsonRequestBehavior.AllowGet);
    }

查看

div class="editor-field">
        @Html.TextBoxFor(m=>m.LocationId,new {data_autocomplete =     Url.Action("QuickSearchLocation", "Inspection")})

脚本

$(document).ready(function () {

$(":input[data-autocomplete]").each(function () {

    $(this).autocomplete({ source: $(this).attr("data-autocomplete")});
});

对我的问题的任何见解都会有所帮助。

【问题讨论】:

  • 请不要将“ASP.NET MVC”简单地称为“MVC”。一种是框架,另一种是与语言无关的设计模式。就像你在谈论 IE 时一直使用“互联网”这个名字一样。
  • @tereško 感谢您的课程,问题已被编辑。

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


【解决方案1】:

自动完成只需要标签或带有值的标签。另一方面,您为它提供了整个 Location 对象。

因此,您应该创建一个辅助类:

public class AutocompleteLocation{
    public AutocompleteLocation(Location location){
        label = location.LocationName;
        value = location.LocationId;
    }
    public string label {get;set;}
    public string value {get;set;}
}

在此之后,您应该像这样更改您的 QuickSearchLocation 控制器方法:

public ActionResult QuickSearchLocation(string term)
{
    return Json(_service.QuickSearchLocation(term).Select(l => new AutocompleteLocation(l)).ToList(), JsonRequestBehavior.AllowGet);
}

您还应该考虑不要返回所有结果,而是只返回前几个(例如 10 个)。

【讨论】:

  • 感谢自动完成功能已恢复,肯定需要开始研究这些帮助类。
猜你喜欢
  • 2011-01-24
  • 1970-01-01
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-09
相关资源
最近更新 更多