【问题标题】:MVC Bootstrap typeahead HtmlHelperMVC Bootstrap 预输入 HtmlHelper
【发布时间】:2013-05-07 16:53:56
【问题描述】:

我是 MVC 的新手,并且正在使用 Twitter 的 Bootstrap 开发一个 MVC4 网站,我们需要一个用于 TypeAhead 的 HtmlHelper。

我获得了 Twitter 引导程序的 HtmlHelper 代码here

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);
    }

就像现在一样,我为 HtmlHelper 提供了一个 IEnumerable 来填充建议框。我不知道如何为此使用我自己的 JsonResult。它还需要是动态的,因为我们需要在网站上具有多个不同项目源的多个实例上使用 HtmlHelper,所有这些都使用 EF 从数据库中提取。

我不喜欢这个解决方案的地方在于 IEnumerable 中的内容显示在 html 源代码中,访问者易于阅读。

有没有办法让 Twitter 的 typeahead.js 有一个 HtmlHelper 并调用 JsonResult 作为项目源,而不是将 JsonResults 编码在 html 中打印给最终用户?

【问题讨论】:

  • 仅供参考,用户也可以通过任何网络检查器工具(现在内置于所有浏览器)轻松查看 JSON 数据。任何客户端控件总是会以某种形式公开其数据。

标签: c# asp.net-mvc asp.net-mvc-4 twitter-bootstrap bootstrap-typeahead


【解决方案1】:

我认为直接使用 typeahead 会容易得多。

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

当然,你可以把它变成一个助手,但我认为这样更容易。 注意:我没有测试这段代码,所以请原谅任何错误,但希望它能给你带来想法。由于该操作是使用 AJAX 调用的,因此它也不会出现在原始页面源中。您还可以将源更改为函数调用,并根据需要定期更新您的操作中的数据。

【讨论】:

  • 谢谢,经过一番研究,我认为这是最好的方法。我现在已经开始工作了。
【解决方案2】:

回复有点晚,但我为您提供了更好的解决方案。使用TwitterBootstrapMvc

它有一个使用 Typehead 的好例子。此外,使用这种方法,您根本不需要自定义 javascript。只需将其包含在侧面的 javascript 文件中即可。

【讨论】:

  • 此项目已从 CodeProject 中删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多