我刚刚使用 MVC 5 模型包装器的 Typeahead.js 实现了 typeahead 功能
http://timdwilson.github.io/typeahead-mvc-model/
一切正常,但我只是不知道如何设置建议下拉列表中显示的项目数量限制。 javascript 是这样的
$('#scrollable-dropdown-menu .typeahead').typeahead(null, {
name: 'countries',
limit: 10, -----> limit set here
source: countries
});
但我看不到 mvc 模型包装器如何实现这一点,有三个重载,其中之一具有“AdditionalViewdata”,也许这就是所需要的?我找不到任何文档,而且似乎没有其他人这样做过(看起来下拉列表中默认为 5)我的后端机制返回超过 5 个结果,它只是没有反映在 html 中
@Html.AutocompleteFor(model => model.Organisation.Org, model => model.Organisation.ORGID, "Autocomplete", "Organisation", false, new { htmlAttributes = new { @class = "form-control" } })
有人可以帮忙吗?
关键是使用linq“Take”
这有效:1)在控制器中创建一个操作并设置 RouteConfig 来启动该操作
public class HomeController : Controller
{
public ActionResult Index20()
{
MyViewModel m = new MyViewModel();
return View(m);
}
创建没有任何类型母版页的视图
添加此视图模型:
public class MyViewModel
{
public string SourceCaseNumber { get; set; }
}
转到管理 Nuget 包或 PM 控制台并添加到 MVC 5 项目 - Typeahead.js for MVC 5 Models by Tim Wilson
将添加的 HtmlHelpers.cs 的命名空间更改为 System.Web.Mvc.Html 并重建
添加这个类:
public class CasesNorm
{
public string SCN { get; set; }
}
将这些方法添加到您的控制器中:
private List<Autocomplete> _AutocompleteSourceCaseNumber(string query)
{
List<Autocomplete> sourceCaseNumbers = new List<Autocomplete>();
try
{
//You will goto your Database for CasesNorm, but if will doit shorthand here
//var results = db.CasesNorms.Where(p => p.SourceCaseNumber.Contains(query)).
// GroupBy(item => new { SCN = item.SourceCaseNumber }).
// Select(group => new { SCN = group.Key.SCN }).
// OrderBy(item => item.SCN).
// Take(10).ToList(); //take 10 is important
CasesNorm c1 = new CasesNorm { SCN = "11111111"};
CasesNorm c2 = new CasesNorm { SCN = "22222222"};
IList<CasesNorm> aList = new List<CasesNorm>();
aList.Add(c1);
aList.Add(c2);
var results = aList;
foreach (var r in results)
{
// create objects
Autocomplete sourceCaseNumber = new Autocomplete();
sourceCaseNumber.Name = string.Format("{0}", r.SCN);
sourceCaseNumber.Id = Int32.Parse(r.SCN);
sourceCaseNumbers.Add(sourceCaseNumber);
}
}
catch (EntityCommandExecutionException eceex)
{
if (eceex.InnerException != null)
{
throw eceex.InnerException;
}
throw;
}
catch
{
throw;
}
return sourceCaseNumbers;
}
public ActionResult AutocompleteSourceCaseNumber(string query)
{
return Json(_AutocompleteSourceCaseNumber(query), JsonRequestBehavior.AllowGet);
}
throw;
}
catch
{
throw;
}
return sourceCaseNumbers;
}
public ActionResult AutocompleteSourceCaseNumber(string query)
{
return Json(_AutocompleteSourceCaseNumber(query), JsonRequestBehavior.AllowGet);
}
信用归于http://timdwilson.github.io/typeahead-mvc-model/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)