23 June 2017 Sudhanshu Ranjan 168

Autocomplete textbox with multi value selected in MVC using JQuery

Hello Guys, in my today’s article I am going to explain how to create autocomplete textbox with multi value selectable using MVC and JQuery. The selected value will not be duplicate in textbox.

So let’s start to implement the autocomplete textbox.

Database – I have created a table (Category) and have some list of categories. (Script Below)



CREATE TABLE [dbo].[Category](
	[CategoryName] [varchar](150) NOT NULL,
	[Description] [nvarchar](max) NULL,
	[IsActive] [bit] NULL,
	[IsDeleted] [bit] NULL,
	[CreatedBy] [int] NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedBy] [int] NULL,
	[ModifiedDate] [datetime] NULL,
 CONSTRAINT [PK_Category] PRIMARY KEY CLUSTERED 
(
	[CategoryName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[Category] ([CategoryName], [Description], [IsActive], [IsDeleted], [CreatedBy], [CreatedDate], [ModifiedBy], [ModifiedDate]) VALUES (N'asp.net', N'', 1, 0, 1, GETDATE(), 0, NULL)
INSERT [dbo].[Category] ([CategoryName], [Description], [IsActive], [IsDeleted], [CreatedBy], [CreatedDate], [ModifiedBy], [ModifiedDate]) VALUES (N'C#', N'', 1, 0, 1, GETDATE(), 0, NULL)
INSERT [dbo].[Category] ([CategoryName], [Description], [IsActive], [IsDeleted], [CreatedBy], [CreatedDate], [ModifiedBy], [ModifiedDate]) VALUES (N'html', N'', 1, 0, 1, GETDATE(), 0, NULL)
INSERT [dbo].[Category] ([CategoryName], [Description], [IsActive], [IsDeleted], [CreatedBy], [CreatedDate], [ModifiedBy], [ModifiedDate]) VALUES (N'javascript', N'', 1, 0, 1, GETDATE(), 0, NULL)
INSERT [dbo].[Category] ([CategoryName], [Description], [IsActive], [IsDeleted], [CreatedBy], [CreatedDate], [ModifiedBy], [ModifiedDate]) VALUES (N'jquery', N'', 1, 0, 1, GETDATE(), 0, NULL)
INSERT [dbo].[Category] ([CategoryName], [Description], [IsActive], [IsDeleted], [CreatedBy], [CreatedDate], [ModifiedBy], [ModifiedDate]) VALUES (N'mvc', N'', 1, 0, 1, GETDATE(), 0, NULL)
INSERT [dbo].[Category] ([CategoryName], [Description], [IsActive], [IsDeleted], [CreatedBy], [CreatedDate], [ModifiedBy], [ModifiedDate]) VALUES (N'sql server', N'', 1, 0, 1, GETDATE(), 0, NULL)
INSERT [dbo].[Category] ([CategoryName], [Description], [IsActive], [IsDeleted], [CreatedBy], [CreatedDate], [ModifiedBy], [ModifiedDate]) VALUES (N'web service', N'', 1, 0, 1, GETDATE(), 0, NULL)

 

Then Create a MVC web application & add controller with respective views. Then I am creating a textbox control in views.

<div>    
    @Html.TextBox("txtSearch")
</div>

 

Create an action method in controller which will return the matched list of Categories and also I have written the logic whatever categories already selected in textbox that will not populate in searched list.

public JsonResult GetCategory(string searchPrefix)
        {
            List<string> category = new List<string>();

            List<string> items = searchPrefix.Split(';').ToList();
            items = items.Select(s => s.Trim()).ToList();

            //Getting extract text to be searched from the list
            string searchItem = items.LastOrDefault().ToString().Trim();

            //Return same if search text is blank or empty
            if (string.IsNullOrEmpty(searchItem))
            {
                return Json(new string[0], JsonRequestBehavior.AllowGet);
            }

            //Populate the items that need to be filtered out
            List<string> excludeItem = new List<string>();
            if (items.Count > 1)
            {
                items.RemoveAt(items.Count - 1);
                excludeItem = items;
            }

            var data = _db.Categories.Where(x => x.CategoryName.Contains(searchItem))
                                        .Where(x => !excludeItem.Contains(x.CategoryName))
                                        .Select(i => i.CategoryName).ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

 

Added JQuery library and stylesheet (for better autocomplete UI) reference on page.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />

Then I am adding JQuery Ajax call script for getting the list of categories on text box autocomplete event. In this script we are calling the action method and passing the searched text prefix.

Once we will get the data we are separating by semicolon(;) for selected category.

<script type="text/javascript">
    $(document).ready(function ()
    {
        $("#txtSearch").autocomplete({
            source: function (request, response)
            {
                $.ajax({
                    url: '@Url.Action("GetCategory", "Home")',
                    data: "{ 'searchPrefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data)
                    {
                        response($.map(data, function (item)
                        {
                            return item;
                        }))
                    },
                    error: function (response)
                    {
                        alert("error :- " + response.responseText);
                    },
                    failure: function (response)
                    {
                        alert("failure :- " + response.responseText);
                    }
                });
            },
            select: function (e, i)
            {
                var text = this.value.split(/;\s*/);
                text.pop();
                text.push(i.item.value);
                text.push("");
                this.value = text.join("; ");
                return false;
            },
            minLength: 1
        });

    });
</script>

Output -

multi_selection_autocomplete_textbox

If it is helpful for you please provide valuable feedback on comment box.
Please share with your friends. Thanks!!

You can share at :

About Author
Sudhanshu Kumar Ranjan | Lead Engineer at HCL Technologies | Expertise in Microsoft Technology | Author | Blogger | Programmer
Know More
Connect with him on Facebook | Google+ | LinkedIn | Twitter

Recommended Post

Leave a comment

About Dotnet Cube

It's my blog - Dotnet Cube, where you will learn and get solutions about programming, web designing and development. I started this website to share my knowledge and experience which might help someone.

You can get more details about me and my blog at About Us page.

Subscribe Newsletter

Subscribe to our monthly newsletter to get the latest industry news, Media Group updates and our current specials.

Follow On Us...

Home | About | Advertise | Copyrights | Privacy | Contact | Admin

Copyrights © 2015-2017 dotnetcube.com. All rights reserved