2011-07-17 34 views
1

以下jQuery自動完成代碼未在MVC3中顯示結果。當我調試代碼時,我可以看到它正確調用了QuickSearchByLastName。有人可以告訴我,如果我的代碼不正確? (我也試過用jquery-1.6.2.min.js沒有運氣)謝謝!MVC3 jQuery自動完成未顯示結果

Index.cshtml:

@using (Ajax.BeginForm(new AjaxOptions 
{ 
    HttpMethod = "GET", 
    InsertionMode = InsertionMode.Replace, 
    UpdateTargetId = "results" 
} 
)) 
{    
    <input type="text" name="q" data-autocomplete="@Url.Action("QuickSearchByLastName","Search")" />     
} 
<div id="results" > 
</div>  


---------------------------------------------------------------- 
Search Controller: 

    public ActionResult QuickSearchByLastName(string term) 
      { 
       using (var context = new CSCContext()) 
       { 
        var searchResults = context.Students 
             .Where(s => s.LastName.Contains(term) && s.IsActive == true) 
             .Take(10) 
             .Select(s => new { label = s.LastName }); 


        return Json(searchResults, JsonRequestBehavior.AllowGet); 
       }     
      } 

_Layout.cshtml: 
    @Content.Script("jquery-1.4.4.min.js", Url)    
    @Content.Script("jquery.unobtrusive-ajax.min.js", Url) 
    @Content.Script("jquery-ui.min.js", Url)  
    @Content.Script("jquery.validate.min.js", Url)  
    @Content.Script("jquery.validate.unobtrusive.min.js", Url)  
    @Content.Script("CSC.js", Url) 
    @RenderSection("scripts", false) 

CSC.js

$(document).ready(function() 
{ 
    $(":input[data-autocomplete]").each(function() 
    { 
     $(this).autocomplete({ 
           source: $(this).attr("data-autocomplete") 
           } 
          ); 
    }); 

}); 

下面的代碼解決了該問題:

public ActionResult QuickSearchByLastName(string term) 
     {   
      var context = new CSCContext(); 
      try 
      { 

       var searchResults = context.Students 
            .Where(s => s.LastName.Contains(term) && s.IsActive == true) 
            .Take(10) 
            .Select(s => new { label = s.LastName }); 


       return Json(searchResults.ToList(), JsonRequestBehavior.AllowGet); 
      } 
      finally 
      { 
       context.Dispose(); 
      }      
     } 
+0

送你的確可以使用JSON用於自動完成插件 –

+0

插件或1.8用戶界面功能? – Buildstarted

回答

5

我嘗試複製您的方案無濟於事,因爲它總是爲我工作。這就是我所做的。

  1. 使用互聯網的模板
  2. HomeController中創建一個新的ASP.NET MVC 3項目:

    public class HomeController : Controller 
    { 
        public ActionResult Index() 
        { 
         return View(); 
        } 
    
        public ActionResult QuickSearchByLastName(string term) 
        { 
         var results = Enumerable 
          .Range(1, 5) 
          .Select(x => new { 
           id = x, 
           label = "label " + x, 
           value = "value " + x 
          }); 
         return Json(results, JsonRequestBehavior.AllowGet); 
        } 
    } 
    
  3. Index.cshtml

    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" type="text/css" media="all" /> 
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script> 
    
    <script type="text/javascript"> 
        $(function() { 
         $(':input[data-autocomplete]').each(function() { 
          $(this).autocomplete({ 
           source: $(this).attr('data-autocomplete') 
          }); 
         }); 
        }); 
    </script> 
    
    @using (Html.BeginForm()) 
    {    
        <input type="text" name="q" data-autocomplete="@Url.Action("QuickSearchByLastName", "Home")" /> 
    } 
    

我用jquery-1.5.1.min.jsjquery-ui-1.8.11.min.js哪些是b ASP.NET MVC 3 RTM默認爲默認。我也試過把它放在Ajax.BeginForm中,並且還導入了默認的不顯眼的腳本,它仍然適用於我。

+0

你認爲這可能是IE8配置的問題嗎? – rk1962

+0

@ rk1962,你是否試過我的代碼來排除這種可能性?在一個全新的項目中?如果有效,那麼問題不在IE8中。如果沒有,我們會看到(但我會感到驚訝)。 –

+0

我剛剛試過你的代碼,它工作正常。所以,這不是IE8問題。 – rk1962

1

出於某種原因,該腳本文件

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script> 

需要包含在頂部,而不是在任何文件底部指定以提高性能。

如果你這樣做,它會工作。

0

我有和rk1962一樣的問題(和一個快速的網絡搜索顯示大量其他人有相同的問題)。我從上面複製了Darin的代碼,它工作。當我從Index.cshtml的頂部獲取腳本並將其放置在單獨的腳本文件中時,它將停止工作 - QuickSearchByLastName不會被調用。

安德魯

1

簡短的回答:參考這篇文章jQuery UI autocomplete with ASP.NET Web API

龍答:

第1步:獲取網絡API準備

讓我們先創建一個網api方法即wi將使用從自動填充文本框發送的搜索詞查詢返回項目列表(藝術家)。在這篇文章中,我沒有使用數據庫,而是使用List來保持這個例子儘可能簡單。

下面是我如何定義我的藝術家類

public class Artist 
{ 
    public int Id { get; set; } 
    public int Name { get; set; } 
}  

接下來,我創建了一個網絡API GET方法將使用在自動完成的文本框,並用LINQ的幫助不大輸入的搜索項會返回匹配結果的列表。

using System.Collections.Generic; 
using System.Linq; 
using System.Web.Http; 

namespace Autocomplete.Controllers 
{ 
    public class ArtistApiController : ApiController 
    { 

     public List<Artist> ArtistList = new List<Artist> 
     { 
      new Artist{Id = 1, Name = "Sonu Nigam"}, 
      new Artist{Id = 2, Name = "Sunidhi Chauhan"}, 
      new Artist{Id = 3, Name = "Shreya Goshal"}, 
      new Artist{Id = 4, Name = "Mohit Chauhan"}, 
      new Artist{Id = 5, Name = "Nihkil Dsouza"}, 
      new Artist{Id = 6, Name = "Kailash Kher"}, 
      new Artist{Id = 7, Name = "Atif Aslam"}, 
      new Artist{Id = 8, Name = "Ali Zafar"}, 
      new Artist{Id = 9, Name = "Shafaqat Ali"}, 
      new Artist{Id = 10, Name = "Shankar Madahevan"} 
     }; 


     // GET api/values 
     public IEnumerable<Artist> Get(string query) 
     { 
      return ArtistList.Where(m => m.Name.Contains(query)).ToList(); 
     } 
    } 
} 

我們的服務器端代碼已準備就緒!時間來測試它。

enter image description here

第2步:客戶端代碼

包括jQuery的ui.js和jquery.ui.css在HTML

<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js" ></script> 
<script type="text/javascript" src="~/Scripts/jquery-ui-1.8.20.min.js" ></script> 
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" /> 

<div id="body"> 
    <label for="autocomplete-textbox">Search : </label> 
    <input type="text" id="autocomplete-textbox" /> 
</div> 

<script type="text/javascript"> 
$(document).ready(function(){ 
$('#autocomplete-textbox').autocomplete({ 
    source: function (request, response) { 
     // prepare url : for example '/api/artistapi?query=sonu 
     var autocompleteUrl = '/api/artistapi' + '?query=' + request.term; 
     $.ajax({ 
      url: autocompleteUrl, 
      type: 'GET', 
      cache: false, 
      dataType: 'json', 
      success: function (json) { 
       // call autocomplete callback method with results 
       response($.map(json, function (data, id) { 
        return { 
         label: data.Name, 
         value: data.Id 
        }; 
       })); 
      }, 
      error: function (xmlHttpRequest, textStatus, errorThrown) { 
       console.log('some error occured', textStatus, errorThrown); 
      } 
     }); 
    }, 
    minLength: 2, 
    select: function (event, ui) { 
     alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value); 
     $('#autocomplete-textbox').val(ui.item.label); 
     return false; 
    } 
}); 
}); 
</script> 

這裏有一點要注意的是,在成功的方法裏面我用了下面的代碼:

response($.map(json, function (data, id) { 
    return { 
     label: data.Name, 
     value: data.Id 
    }; 
})); 

data.Id and data.Name被使用,因爲在ajax響應中(如下所示)數據以此格式返回。

enter image description here

3步:測試&輸出:

enter image description here

here