2010-11-18 70 views
1

我正在閱讀MVC 2 in Action一書。有關自動完成的章節已作爲參考結束。 在控制器中,返回的Json結果不會轉換爲自動完成列表。這本書沒有使用Json,但我不能使用他們的替代品與一個通用的列表。MVC:無法自動完成工作

所以我的觀點是;

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SHP.WebUI.Models.HolidayRequestViewModel>" %> 
<script type="text/javascript" language="javascript"> 
    $(document).ready(function() { 
     $("input#SearchText").autocomplete('<%: Url.Action("FindNames", "Employee") %>'); 
    }); 

</script> 
<p>You must make sure that the correct person to approve your Annual Leave is currently selected</p> 
<p>Your current approver is <%: Html.DisplayFor(model => model.ApproverName) %></p> 
<p>If you want to change your approver, enter his/her name here and make your selection.</p> 
<p><%: Html.TextBoxFor(model => model.SearchText) %></p> 
<div id="test-panel" class="ui-state-default"> This panel will disappear on command.</div> 

而我的控制器是;

public JsonResult FindNames(string q) 
    { 
     List<EmployeeName> filteredEmployees = 
      Employee.GetAllCurrentEmployeesNames().Where(x => x.Fullname.ToLower().Contains(q.ToLower())).ToList(); 
     return Json(filteredEmployees, JsonRequestBehavior.AllowGet); 
    } 

* EDITED * 與發送參數的問題已得到修復,通過使用 「串Q」。明顯的呃?現在是將JSON返回到自動完成列表中的一種情況。

+0

我不知道ASP.NET自動完成機制,但我期望問題是URL上參數的名稱。自動完成生成的URL是什麼 - 命名參數是什麼?你有沒有爲這個行動設置特定的路線? – Rup 2010-11-18 14:30:16

回答

4

如果您使用的是jquery UI autocomplete,則查詢字符串參數默認爲term。所以:

public ActionResult FindNames(string term) 

當然,這可能是個性化:

$('input#SearchText').autocomplete({ 
    source: function(request, response) { 
     $.ajax({ 
      url: '<%: Url.Action("FindNames", "Employee") %>', 
      dataType: 'json', 
      data: { searchText: request.term }, 
      success: function(data) { 
       response(data); 
      } 
     }); 
    } 
}); 

的問題是它是否是值得的。

+0

你是對的。其實我應該複製我的書,它指定FindNames(字符串q),所以q而不是term。爲什麼在這個應該是,我不知道。 – arame3333 2010-11-18 14:47:58

+0

@ arame3333,如果我沒有記錯的話,'q'被更早的jQuery自動完成插件所使用,現在已經棄用jQuery UI,我推薦你使用這個插件。 – 2010-11-18 14:51:11

+0

實際上從這本書開始,我使用這個插件; https://github.com/dyve/jquery.autocomplete/blob/master/index.html現在已經有一年多了。 – arame3333 2010-11-18 15:16:32