【发布时间】: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
我不喜欢这个解决方案的地方在于 IEnumerable
有没有办法让 Twitter 的 typeahead.js 有一个 HtmlHelper 并调用 JsonResult 作为项目源,而不是将 JsonResults 编码在 html 中打印给最终用户?
【问题讨论】:
-
仅供参考,用户也可以通过任何网络检查器工具(现在内置于所有浏览器)轻松查看 JSON 数据。任何客户端控件总是会以某种形式公开其数据。
标签: c# asp.net-mvc asp.net-mvc-4 twitter-bootstrap bootstrap-typeahead