2016-07-30 6 views
1

jquery 자동 완성을 사용하여 ASP.NET MVC에서 자동 완성 텍스트 상자를 만들려고합니다. ASP.NET MVC에서 자동 완성 만들기 오류

내 Index.cshtml입니다 :

<div class="autocomplete"> 
    @Html.TextBox("item", null, new { id = "autocomplete-textbox", @class = "form-control" }); 
    <input type="submit" value="Submit" id="autocomplete-button"/> 
</div> 

<script> 
    $(function() { 
     $('#autocomplete-textbox').autocomplete({ 
      source: '@Url.Action("AutoComplete")', 
      minlength: 1 
     }); 
    }); 
</script> 

그리고 이것은 내 집 컨트롤러 방법 :

public JsonResult AutoComplete(string item) 
    { 

     IEnumerable<string> itemsList = new[] { "Ana", "are", "mere", "pere", "papaia", "Aaa", "Ab", "An" }; 
     IEnumerable<string> filteredResults = null; 

     if (string.IsNullOrEmpty(item)) 
     { 
      filteredResults = itemsList; 
     } 
     else 
     { 
      filteredResults = itemsList.Where(s => s.IndexOf(item, StringComparison.InvariantCultureIgnoreCase) >= 0); 
     } 

     return Json(filteredResults, JsonRequestBehavior.AllowGet); 
    } 

내 문제는 JsonResult 자동 완성의 매개 변수 항목이 항상 null이며, 그래서이다 항상 전체 목록으로 JSON 응답을받습니다. 내가 무엇을 할 수 있을지 ?

감사합니다, 마커스

답변

0

은 기본적으로의 jQuery 자동 완성 플러그인은 귀하의 브라우저 도구를 dev에 당신이 열 경우이를 볼 수 있습니다 term이 아닌 항목 (라는 쿼리 문자열 PARAM와 값의 입력을 보내드립니다 -> 네트워크 탭).

그래서 또한 term

public JsonResult AutoComplete(string term) 
{ 
    // use term for your checkings 
    // to do : Return something  
} 

에 서버 작업 메서드 매개 변수의 이름을 변경, 난 당신의 코드에서 또 다른 문제를 발견했습니다. 변수 변수가 비어 있지 않으면 필터링 된 결과 (Where 메서드 호출의 결과)를 filteredResults 변수로 설정해야합니다.

if (string.IsNullOrEmpty(term)) 
{ 
    filteredResults = itemsList; 
} 
else 
{ 
    filteredResults = itemsList 
      .Where(s => s.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0); 
} 
+1

좋아, 대단히 감사합니다. 이것은 도움이되었습니다. – Marcus

0

당신은 기본적으로 JQuery와 자동 완성 위젯은 "용어"로라는 변수에 값을 전송 당신이 컨트롤러에서 사용하는 "용어"와 같은 매개 변수의 이름을 가지고 그냥 것이다. 따라서 단지 다음과 같이 변경합니다

공공 JsonResult 자동 완성 (문자열 용어) {

IEnumerable<string> itemsList = new[] { "Ana", "are", "mere", "pere", "papaia", "Aaa", "Ab", "An" }; 
    IEnumerable<string> filteredResults = null; 

    if (string.IsNullOrEmpty(term)) 
    { 
     filteredResults = itemsList; 
    } 
    else 
    { 
     filteredResults = itemsList.Where(s => s.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0); 
    } 

    return Json(filteredResults, JsonRequestBehavior.AllowGet); 
}