2013-04-05 98 views
1

從回覆的幫助後,我改變了我的代碼url.action自動完成

@Html.TextBoxFor(per => per.Hospital, new { style = "width:220px", @maxlength = "50", data_autocomplete = Url.Action("HospitalList", "Person") }) 

我jQuery是

$(document).ready(function() {   
    $('input[data_autocomplete]').each(function() { 
     var url = $(this).data('autocomplete'); 
     $(this).autocomplete({ 
      source: function (request, response) { 
       $.getJSON(url, { 
        term: request.term 
       }, response); 
      } 
     }); 
    }); 
}); 

而創建的一個新的Action結果

public ActionResult HospitalList(string term) 
    { 
     List<string> result = new List<string>(); 
     result.Add("Hospital 1"); 
     result.Add("NYUMC"); 
     result.Add("Christ"); 
     result.Add("Bellevue"); 
     result.Add("NewYork-Presbyterian"); 
     result.Add("North Central Bronx Hospital");    

     return Json(result , JsonRequestBehavior.AllowGet); 
    } 

現在我在哪裏wromg。我只看到一個文本框,沒有自動完成的行爲。我應該包括任何jQuery庫它的工作

+1

你在使用自動完成功能? jQuery UI? – 2013-04-05 17:32:09

+0

我沒有使用任何東西,我只是想讓textboxfor表現得像自動完成一樣。我對MVC和jquery很新。上面列出了我所做的所有事情。 – DotNetBeginner 2013-04-05 17:40:45

+0

「HTML」中沒有自動完成功能。如果你想使用一個,你將不得不使用一個插件。 jQuery UI自動完成是一個這樣的插件。你需要在你的視圖中引用jquery.js和'jquery-ui.js'。您還應該閱讀一些文檔以熟悉一些基本的JavaScript。 – 2013-04-05 20:57:33

回答

0

你還沒有顯示你正在使用哪個自動完成插件。如果是jQuery UI autocomplete,你可以從你的控制器動作返回過濾後的結果爲JSON:

[HttpGet] 
public ActionResult PersonSearch(string term) 
{ 
    // The term parameter will contain the value entered by the user in the textbox. 
    // here you could use it and query your database in order to filter the results. 
    string[] result = new string[] 
    { 
     "filtered value 1", 
     "filtered value 2", 
     "filtered value 3", 
     "filtered value 4", 
    }; 

    return Json(result, JsonRequestBehavior.AllowGet); 
} 

最後,你會附加插件:

$(function() { 
    $('input[data-autocomplete]').each(function() { 
     var url = $(this).data('autocomplete'); 
     $(this).autocomplete({ 
      source: function(request, response) { 
       $.getJSON(url, { 
        term: request.term 
       }, response); 
      } 
     }); 
    }); 
}); 

注意如何控制行動採取term參數應該返回一個字符串列表作爲JSON。

+0

你好Darin謝謝你的回覆。如果你在上面看到我的控制器,我現在根據你的解釋返回一個視圖,我必須返回jason,我如何將視圖和jason一起返回。我沒有使用任何自動完成插件。 – DotNetBeginner 2013-04-05 17:56:22

+0

您無法同時返回JSON和視圖。這沒有意義。爲了使用jQuery UI自動完成插件,請確保您已在頁面中包含第一個「jquery.js」和「jquery-ui.js」腳本。最後你可以在你的自定義腳本中使用'.autocomplete'。 – 2013-04-05 20:55:44

+0

謝謝Darian我終於搞定了...... – DotNetBeginner 2013-04-05 21:22:39