2

我是相當新的MVC和工作與Twitter的Bootstrap MVC4網站,我們需要一個HtmlHelper爲TypeAheadMVC Bootstrap typeahead HtmlHelper

我得到的代碼爲Twitter的引導here一個的HtmlHelper:

public static MvcHtmlString TypeaheadFor<TModel, TValue>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TValue>> expression, 
    IEnumerable<string> source, 
    int items = 8) 
{ 
    if (expression == null) 
     throw new ArgumentNullException("expression"); 

    if (source == null) 
     throw new ArgumentNullException("source"); 

    var jsonString = new JavaScriptSerializer().Serialize(source); 

    return htmlHelper.TextBoxFor(
     expression, 
     new { 
      autocomplete = "off", 
      data_provide = "typeahead", 
      data_items = items, 
      data_source = jsonString 
     } 
    ); 
} 

我還寫了下面的代碼爲預輸入提供JSON:

 public JsonResult Autocomplete(string input) { 
     var model = db.Users 
         .Select(g => new { 
          label = g.Name.StartsWith(input) 
         }); 
     return Json(model, JsonRequestBehavior.AllowGet); 
    } 

因爲它是現在,我提供帶IEnumerable的HtmlHelper < string>來填充建議框。我無法弄清楚如何使用我自己的JsonResult。它也需要是動態的,因爲我們需要網站上multipe實例的HtmlHelper,它有幾個不同的項目源,都是使用EF從數據庫中提取的。

我不喜歡這個解決方案是IEnumerable < string>的內容顯示在html源代碼中,對訪問者來說很容易讀取。

有沒有辦法讓Tweets的HtmlHelper typeahead.js和調用JsonResult作爲項目源,並且沒有將JsonResults編碼在HTML中打印到最終用戶?

+0

只是一個簡單的參考,JSON數據也很容易通過任何Web檢查器工具(現在內置於所有瀏覽器)顯示給用戶。任何客戶端控制總是會以某種形式公開其數據。 – Terry 2013-05-07 20:41:33

回答

1

我認爲直接使用typeahead會容易得多。

$(function() { 
    // get your list 
    $.getJSON('/Controller/Autocomplete', function (allData) { 
     $('#your-element').typeahead({source: allData}); 
    }; 
}); 

你當然可以把它變成幫手,但我認爲這樣更容易。 注:我沒有測試這個代碼,所以請原諒任何錯誤,但希望它給你的想法。由於該動作是使用AJAX調用的,因此它也不會在原始頁面源中。您還可以將源更改爲函數調用,並根據需要定期更新您的操作中的數據。

+0

謝謝,經過一番研究,我認爲這是最好的方法。我現在開始工作了。 – Michiel 2013-05-09 09:17:51

-3

有點晚迴應,但我有更好的解決方案給你。使用TwitterBootstrapMvc

它有一個使用Typehead的好例子。另外,使用這種方法,您根本不需要自定義JavaScript。只要將它包含在側面的javascript文件中,並忘記它。

+0

該項目已從CodeProject中刪除。 – Rogier 2014-10-30 22:55:38