Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9294231
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T21:19:25+00:00 2026-06-18T21:19:25+00:00

I need help writing the jquery/ajax to fill a Select2 dropdown box. For those

  • 0

I need help writing the jquery/ajax to fill a Select2 dropdown box.

For those who don’t know what Select2 is, it is a javascript extension to provide Twitter Bootstrap looks and search / type-ahead functionality to an html select list dropdown box. For more information look at the examples here: Select2 Github page


UPDATED – Solved!


So I finally put this all together, and the solution to my problems was that I was missing functions to format the results and the list selection. The code below produces a functioning Select2 dropbox with type-ahead perfectly.

Json Method on Controller:

public JsonResult FetchItems(string query)
{
    DatabaseContext dbContext = new DatabaseContext(); //init dbContext
    List<Item> itemsList = dbContext.Items.ToList(); //fetch list of items from db table
    List<Item> resultsList = new List<Item>; //create empty results list
    foreach(var item in itemsList)
    {   
        //if any item contains the query string
        if (item.ItemName.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0) 
        {
            resultsList.Add(item); //then add item to the results list
        }
    }
    resultsList.Sort(delegate(Item c1, Item c2) { return c1.ItemName.CompareTo(c2.ItemName); }); //sort the results list alphabetically by ItemName
    var serialisedJson = from result in resultsList //serialise the results list into json
        select new
        {
            name = result.ItemName, //each json object will have 
            id = result.ItemID      //these two variables [name, id]
        };
    return Json(serialisedJson , JsonRequestBehavior.AllowGet); //return the serialised results list
}

The Json controller method above returns a list of serialised Json objects, whose ItemName contains the string ‘query’ provided (this ‘query’ comes from the search box in the Select2 drop box).

The code below is the Javascript in the view(or layout if you prefer) to power the Select2 drop box.

Javascript:

$("#hiddenHtmlInput").select2({
    initSelection: function (element, callback) {
        var elementText = "@ViewBag.currentItemName";
        callback({ "name": elementText });
    },
    placeholder: "Select an Item",
    allowClear: true,
    style: "display: inline-block",
    minimumInputLength: 2, //you can specify a min. query length to return results
    ajax:{
        cache: false,
        dataType: "json",
        type: "GET",
        url: "@Url.Action("JsonControllerMethod", "ControllerName")",
        data: function (searchTerm) {
            return { query: searchTerm };
        },
        results: function (data) { 
            return {results: data}; 
        }
    },
    formatResult: itemFormatResult,
    formatSelection: function(item){
        return item.name;
    }
    escapeMarkup: function (m) { return m; }
});

Then in the body of the view you need a hidden Input element, which Select2 will render the dropbox to.

Html:

<input id="hiddenHtmlInput" type="hidden" class="bigdrop" style="width: 30%" value=""/>

Or attach a MVC Razor html.hidden element to your view model to enable you to post the picked item Id back to the server.

Html (MVC Razor):

@Html.HiddenFor(m => m.ItemModel.ItemId, new { id = "hiddenHtmlInput", @class = "bigdrop", style = "width: 30%", placeholder = "Select an Item" })
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T21:19:27+00:00Added an answer on June 18, 2026 at 9:19 pm

    Solved! Finally.

    The full jquery is below, what was needed were two functions to format the returned results from the controller. This is because the dropbox needs some html markup to be wrapped around the results in order to be able to display them.

    Also contractID was needed as an attribute in the controller as without it results were shown in the dropdown, but they could not be selected.

    $("#contractName").select2({
        placeholder: "Type to find a Contract",
        allowClear: true,
        minimumInputLength: 2,
        ajax: {
            cache: false,
            dataType: "json",
            type: "GET",
            url: "@Url.Action("FetchContracts", "Leads")",
            data: function(searchTerm){
                return { query: searchTerm };
            },
            results: function(data){
                return { results: data };
            }
        },
        formatResult: contractFormatResult,
        formatSelection: contractFormatSelection,
        escapeMarkup: function (m) { return m; }
    });
    
    
    function contractFormatResult(contract) {
        var markup = "<table class='contract-result'><tr>";
        if (contract.name !== undefined) {
            markup += "<div class='contract-name'>" + contract.name + "</div>";
        }
        markup += "</td></tr></table>"
        return markup;
    }
    
    function contractFormatSelection(contract) {
        return contract.name;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need help writing a piece of JQuery using the slideToggle(), that is reusable.
I am completely new to Javascript/jquery world and need some help. Right now, I
I need help writing Jquery to disable a group of radio button when one
Here is what the html looks like, I need help writing the jquery? Initially
Need help writing a script downloads data from google insight using c# this is
I need some help writing an http client. The trouble comes when I try
I need some help writing a regex. I have the following strings, xxx.yyy.wwwwwaaa_IN_123 xxx.rrrttttt_IN_12355
I'm new to web programming, so I need some help. I am writing a
I am writing a simple accordion with just javascript. I need to place an
jQuery - ajax success parameter i wanna know how to give a object method

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.