استفاده از افزونه Typeahead مجموعه Twitter Bootstrap در ASP.NET MVC
نویسنده: وحید نصیری
تاریخ: ۱۳۹۲/۰۳/۲۲ ۸:۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace Mvc4TwitterBootStrapTest.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
var array = new[]
{
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica",
"Antigua and/or Barbuda"
};
ViewBag.JsonString = new JavaScriptSerializer().Serialize(array);
return View();
}
}
}@{
ViewBag.Title = "Index";
}
<h2>
Typeahead</h2>
@Html.TextBox("search", null, htmlAttributes:
new
{
autocomplete = "off",
data_provide = "typeahead",
data_items = 8,
data_source = @ViewBag.JsonString
})<input autocomplete="off" data-items="8" data-provide="typeahead" data-source="["Afghanistan","Albania","Algeria","American Samoa","Andorra","Angola","Anguilla","Antarctica","Antigua and/or Barbuda"]" id="search" name="search" type="text" value="" />
public static MvcHtmlString TypeaheadFor<TModel, TValue>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TValue>> expression,
IEnumerable<string> source,
int items = 8)
{
var jsonString = new JavaScriptSerializer().Serialize(source);
return htmlHelper.TextBoxFor(
expression,
new
{
autocomplete = "off",
data_provide = "typeahead",
data_items = items,
data_source = jsonString
}
);
}using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace Mvc4TwitterBootStrapTest.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public JsonResult GetNames(string term)
{
var array = new[]
{
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica",
"Antigua and/or Barbuda"
};
var results = array.Where(n =>
n.StartsWith(term, StringComparison.OrdinalIgnoreCase));
return Json(results.ToArray(), JsonRequestBehavior.AllowGet);
}
}
}@{
ViewBag.Title = "Index";
var url = Url.Action("GetNames", "Home");
}
<h2>
Typeahead</h2>
@Html.TextBox("search", null, htmlAttributes:
new
{
autocomplete = "off",
data_provide = "typeahead",
data_items = 8
})
@section JavaScript
{
<script type="text/javascript">
$(function () {
$('#search').typeahead({
source: function (term, process) {
return $.getJSON('@url', { term: term }, function (data) { return process(data); });
}
});
});
</script>
}$('.typeahead').typeahead({
matcher: function(item) {
// آیتم مقداری است که باید برای تطابق بررسی شود
// this.query کوئری جاری را بر میگرداند.
return true // اگر آیتم تطابق داشته است
}
}) matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
} matcher: function (item) {
return true;
} $('.typeahead').typeahead({
highlighter: function(item){
return "<div>.......</div>";
}
});