2012-11-02 50 views
1

ASP.NET MVC和編程的新手,我已經搜索這個主題的材料的高低,但沒有找到具體的答案爲我的特定問題。與WCF服務綁定的jQuery自動完成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")}); 
}); 

對我的問題,任何有識之士將是有益的。

+0

請停止將「ASP.NET MVC」簡稱爲「MVC」。一個是框架,而另一個是獨立於語言的設計模式。這就像你在談論IE時繼續使用「互聯網」這個名字。 –

+0

@tereško感謝您的教訓,問題已編輯。 – WiseGuy

回答

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個)。

+1

感謝人們的自動完成備份,肯定需要開始尋找那些幫助類。 – WiseGuy