Home > DeveloperSection > Beginner > Bootstrap Tokenfield and autocomplete

Bootstrap Tokenfield and autocomplete


ASP.Net Bootstrap  Bootstrap Typehead  Autocomplete 
Ratings:
0 Comment(s)
 8415  View(s)
Rate this:

Bootstrap Tokenfield and autocomplete

Hi everyone in this article I’m explaining about bootstrap tokenfield and autocomplete.

Description:

JQuery Bootstrap Tokenfield is a pretty jQuery plugin that takes advantage of jQuery and Twitter's Bootstrap to manage tags / tokens in an input field.

Bootstrap Tags Input is a jQuery plugin that allows you to add, remove, and categorize tags with Twitter Bootstrap user interface.

Features:

1.       Keyboard support (arrow keys, Backspace, delete, Ctrl + A, Cmd + A, Ctrl + C, Cmd + C, Ctrl + V and Cmd + V)Copy & paste support

2.       Copy & paste support

3.       Validation states

4.       jQuery UI Autocomplete support

 

In this post describe about how to validate tag, get server side, post and autocomplete etc.

 

Open visual studio >> File >> New Project >> ASP.NET MVC 4 Web Application

 

Give application name and click ok

Then after a window open and select empty template

 

After create your project make database and table

Create Table TokenField

(

       Id int identity(1,1) primary key,

       Tag NVarchar(max)

)

 

Connect with database and use this table for insert tag and populate tag

Download these css and javascript files from: http: //sliptree.github.io/bootstrap-tokenfield/

<link href="~/Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

<link href="~/Content/bootstrap/css/bootstrap-tokenfield.min.css" rel="stylesheet" />

<link href="~/Content/bootstrap/css/tokenfield-typeahead.min.css" rel="stylesheet" />

<script src="~/Scripts/jquery-2.1.1.min.js"></script>

<script src="~/Scripts/bootstrap/js/bootstrap.min.js"></script>

<script src="~/Scripts/bootstrap/js/bootstrap-tokenfield.min.js"></script>

<script src="~/Scripts/bootstrap/js/typeahead.bundle.min.js"></script>

 

Add Controller:

HomeController Code:

using Bootstrap_TokenField.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace Bootstrap_TokenField.Controllers

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

 

        MyDBEntities db = new MyDBEntities();

 

        public ActionResult Index()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult Index(TokenField model)

        {

            if (ModelState.IsValid && !string.IsNullOrEmpty(model.Tag))

            {

                db.TokenFields.Add(model);

                db.SaveChanges();

            }

            return View();

        }

 

        public ActionResult GetTag()

        {

            var token = string.Join(",", db.TokenFields.ToList().Select(x => x.Tag).ToList());

            return Json(new { data = token.ToString().Split(',') }, JsonRequestBehavior.AllowGet);

        }

    }

}

 

Add View:

Index Code:

@model Bootstrap_TokenField.Models.TokenField

@{

    ViewBag.Title = "Index";

}

<link href="~/Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

<link href="~/Content/bootstrap/css/bootstrap-tokenfield.min.css" rel="stylesheet" />

<link href="~/Content/bootstrap/css/tokenfield-typeahead.min.css" rel="stylesheet" />

<script src="~/Scripts/jquery-2.1.1.min.js"></script>

<script src="~/Scripts/bootstrap/js/bootstrap.min.js"></script>

<script src="~/Scripts/bootstrap/js/bootstrap-tokenfield.min.js"></script>

<script src="~/Scripts/bootstrap/js/typeahead.bundle.min.js"></script>

<div class="clearfix">&nbsp;</div>

<div class="clearfix">&nbsp;</div>

<div class="container">

    @using (Html.BeginForm("Index", "Home", FormMethod.Post))

    {

        <div class="row">

            <div class="col-md-4 col-md-offset-4">

                @Html.TextBoxFor(m => m.Tag, new { @class = "form-control", @id = "tokenfield" })

            </div>

        </div>

        <div class="clearfix">&nbsp;</div>

        <div class="row">

            <div class="col-md-4 col-md-offset-4 text-right">

                <input type="submit" value="Save" class="btn btn-info" id="submittoken" />

            </div>

        </div>

    }

</div>

 

Javascript Code:

$(document).ready(function () {

        var token = [];

        var engine;

        $.get("Home/GetTag", function (response) {

            $.each(response.data, function (i, v) {

                token.push({ value: v });

                console.log(v);

            });

            engine = new Bloodhound({

                local: token,

                datumTokenizer: function (d) {

                    return Bloodhound.tokenizers.whitespace(d.value);

                },

                queryTokenizer: Bloodhound.tokenizers.whitespace

 

            });

            engine.initialize();

            console.log(token);

            $('#tokenfield').on('tokenfield:createtoken', function (e) {

                var data = e.attrs.value.split('|')

                e.attrs.value = data[1] || data[0]

                e.attrs.label = data[1] ? data[0] + ' (' + data[1] + ')' : data[0]

            }).on('tokenfield:createdtoken', function (e) {

                var re = /\S+\S+\.\S+/

                var valid = re.test(e.attrs.value)

                if (!valid) {

                    $(e.relatedTarget).addClass('invalid')

                }

            }).on('tokenfield:edittoken', function (e) {

                if (e.attrs.label !== e.attrs.value) {

                    var label = e.attrs.label.split(' (')

                    e.attrs.value = label[0] + '|' + e.attrs.value

                }

            }).on('tokenfield:removedtoken', function (e) {

            }).tokenfield({

                typeahead: [null, { source: engine.ttAdapter() }]

            });

        });

    });

 

Output:


In my next post i'll explain about CheckBoxList Example in ASP.NET MVC 4


Don't want to miss updates? Please click the below button!

Follow MindStick