locked
ASP.NET MVC5 HOW TO CONVERT TEXTBOX TO DROPDOWN ? RRS feed

  • Question

  • User-366701151 posted

    This is a working code , but want i want to do is how can i change the textbox                @Html.TextBoxFor(model => model.CategoryID,   new { @class = "form-control" })

     into dropdowncolumn , with all the same functionalities has ,i mean autocomplete option like that :

    @Html.TextBoxFor(model => model.CategoryID,   new { @class = "form-control" })
    @section scripts{
        <script src="~/Scripts/jquery-ui-1.12.1.js"></script>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script>
            $(function () {
                $("#CategoryID").autocomplete({
                    source: function (request, response) {
                    $.ajax({
                        url: '@Url.Action("AutoComplete")',
                        datatype: "json",
                        data: {
                            term: request.term
                        },
                        success: function (data) {
                            response($.map(data, function (val, item) {
                                return {
                                    label: val.Name + "     |       " + val.Description,
                                    value: val.Name,
                                    CategoryId: val.ID,
                                     Description: val.Description
                                }
                            }))
                        }
                    })
                },
                select: function (event, ui) {
                    $.get("/Home/GetSProductList", { CategoryID: ui.item.CategoryId }, function (data) {
                        $("#ProductID").empty();
                        $.each(data, function (index, row) {
                            $("#ProductID").append("<option value='" + row.ProductID + "'>" + row.ProductName + "</option>")
                        });
     
                    });
     
                    $.get("/Home/GetOrderList", { ProductID: $("#ProductID").val() }, function (data) {
                        $("#OrderID").empty();
                        $.each(data, function (index, row) {
                            $("#OrderID").append("<option value='" + row.OrderID + "'>" + row.OrderID + "</option>")
                        });
     
                    });
     
     
                }
     
     
     
                })
            })
        </script>
    }

     

    public ActionResult Index()
          {
     
     
              List<Category> CategoryList = db.Categories.ToList();
     
     
              ViewBag.CategoryList = new SelectList(CategoryList , "CategoryID" , "CategoryName");
              return View();
          }
    

     

    public ActionResult AutoComplete(string term)
          {
              if (!String.IsNullOrEmpty(term))
              {
                  var list = db.Categories.Where(c => c.CategoryName.ToUpper().Contains(term.ToUpper())).Select(c => new { Name = c.CategoryName, ID = c.CategoryID , Description= c.Description})
                      .ToList();
                  return Json(list, JsonRequestBehavior.AllowGet);
              }
              else
              {
                  var list = db.Categories.Select(c => new { Name = c.CategoryName, ID = c.CategoryID, Description = c.Description })
                      .ToList();
                  return Json(list, JsonRequestBehavior.AllowGet);
              }
          }

     



    Friday, December 8, 2017 9:28 AM

Answers

  • User1400794712 posted

    Hi ddgg,

    The link bruce post is using dropdownlist. Then according to your needs, you can modify the code to:

    Controller:

    public ActionResult AutoDropDownList()
    {
        var list = new List<SelectListItem>();
        foreach (var item in db.Categories)
        {
            list.Add(new SelectListItem { Text = item.CategoryName + "|" + item.Description, Value = item.CategoryID.ToString() });
        }
        ViewBag.CategoryListNew = list;
        return View();
    }

    View:

    @model Test.Models.Category
    @{ 
        Layout = null;
    }
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>jQuery UI Autocomplete - Combobox</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="/resources/demos/style.css">
        <style>
            .custom-combobox {
                ;
                display: inline-block;
            }
    
            .custom-combobox-toggle {
                ;
                top: 0;
                bottom: 0;
                margin-left: -1px;
                padding: 0;
            }
    
            .custom-combobox-input {
                margin: 0;
                padding: 5px 10px;
            }
        </style>
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script>
      $( function() {
        $.widget( "custom.combobox", {
          _create: function() {
            this.wrapper = $( "<span>" )
              .addClass( "custom-combobox" )
              .insertAfter( this.element );
    
            this.element.hide();
            this._createAutocomplete();
            this._createShowAllButton();
          },
    
          _createAutocomplete: function() {
            var selected = this.element.children( ":selected" ),
              value = selected.val() ? selected.text() : "";
    
            this.input = $( "<input>" )
              .appendTo( this.wrapper )
              .val( value )
              .attr( "title", "" )
              .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
              .autocomplete({
                delay: 0,
                minLength: 0,
                source: $.proxy( this, "_source" )
              })
              .tooltip({
                classes: {
                  "ui-tooltip": "ui-state-highlight"
                }
              });
    
            this._on( this.input, {
              autocompleteselect: function( event, ui ) {
                ui.item.option.selected = true;
                this._trigger( "select", event, {
                  item: ui.item.option
                });
              },
    
              autocompletechange: "_removeIfInvalid"
            });
          },
    
          _createShowAllButton: function() {
            var input = this.input,
              wasOpen = false;
    
            $( "<a>" )
              .attr( "tabIndex", -1 )
              .attr( "title", "Show All Items" )
              .tooltip()
              .appendTo( this.wrapper )
              .button({
                icons: {
                  primary: "ui-icon-triangle-1-s"
                },
                text: false
              })
              .removeClass( "ui-corner-all" )
              .addClass( "custom-combobox-toggle ui-corner-right" )
              .on( "mousedown", function() {
                wasOpen = input.autocomplete( "widget" ).is( ":visible" );
              })
              .on( "click", function() {
                input.trigger( "focus" );
    
                // Close if already visible
                if ( wasOpen ) {
                  return;
                }
    
                // Pass empty string as value to search for, displaying all results
                input.autocomplete( "search", "" );
              });
          },
    
          _source: function( request, response ) {
            var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
            response(this.element.children("option").map(function () {
                var text = $(this).text();
                //Here needs changes 
                //if (this.value && (!request.term || matcher.test(text)))
                if (this.value && (!request.term || matcher.test(text.split("|")[0]) ) )
                return {
                  label: text,
                  value: text,
                  option: this
                };
            }) );
          },
    
          _removeIfInvalid: function( event, ui ) {
            // Selected an item, nothing to do
            if ( ui.item ) {
              return;
            }
            // Search for a match (case-insensitive)
            var value = this.input.val(),
              valueLowerCase = value.toLowerCase(),
              valid = false;
            this.element.children( "option" ).each(function() {
              if ( $( this ).text().toLowerCase() === valueLowerCase ) {
                this.selected = valid = true;
                return false;
              }
            });
    
            // Found a match, nothing to do
            if ( valid ) {
              return;
            }
    
            // Remove invalid value
            this.input
              .val( "" )
              .attr( "title", value + " didn't match any item" )
              .tooltip( "open" );
            this.element.val( "" );
            this._delay(function() {
              this.input.tooltip( "close" ).attr( "title", "" );
            }, 2500 );
            this.input.autocomplete( "instance" ).term = "";
          },
    
          _destroy: function() {
            this.wrapper.remove();
            this.element.show();
          }
        });
    
        $( "#combobox" ).combobox();
        $( "#toggle" ).on( "click", function() {
          $( "#combobox" ).toggle();
        });
      } );
        </script>
    </head>
    <body>
    
        <div class="ui-widget">
            <label>Your preferred programming language: </label>
            @Html.DropDownList("combobox",ViewBag.CategoryListNew as IEnumerable<SelectListItem>, "--Select--")
        </div>
        <button id="toggle">Show underlying select</button>
    
    
    </body>
    </html>

    Best Regards,

    Daisy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 11, 2017 7:53 AM

All replies

  • User-474980206 posted

    its not clear what is the new UI behavior you want. 

    Friday, December 8, 2017 4:02 PM
  • User-366701151 posted

    i have a autocomplete textbox , i want to convert it into autocomplete dropdrownlist

    Sunday, December 10, 2017 2:40 PM
  • User-474980206 posted

    maybe the autocomplete combo is what your want:

    https://jqueryui.com/autocomplete/#combobox

    Sunday, December 10, 2017 7:59 PM
  • User1400794712 posted

    Hi ddgg,

    The link bruce post is using dropdownlist. Then according to your needs, you can modify the code to:

    Controller:

    public ActionResult AutoDropDownList()
    {
        var list = new List<SelectListItem>();
        foreach (var item in db.Categories)
        {
            list.Add(new SelectListItem { Text = item.CategoryName + "|" + item.Description, Value = item.CategoryID.ToString() });
        }
        ViewBag.CategoryListNew = list;
        return View();
    }

    View:

    @model Test.Models.Category
    @{ 
        Layout = null;
    }
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>jQuery UI Autocomplete - Combobox</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="/resources/demos/style.css">
        <style>
            .custom-combobox {
                ;
                display: inline-block;
            }
    
            .custom-combobox-toggle {
                ;
                top: 0;
                bottom: 0;
                margin-left: -1px;
                padding: 0;
            }
    
            .custom-combobox-input {
                margin: 0;
                padding: 5px 10px;
            }
        </style>
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script>
      $( function() {
        $.widget( "custom.combobox", {
          _create: function() {
            this.wrapper = $( "<span>" )
              .addClass( "custom-combobox" )
              .insertAfter( this.element );
    
            this.element.hide();
            this._createAutocomplete();
            this._createShowAllButton();
          },
    
          _createAutocomplete: function() {
            var selected = this.element.children( ":selected" ),
              value = selected.val() ? selected.text() : "";
    
            this.input = $( "<input>" )
              .appendTo( this.wrapper )
              .val( value )
              .attr( "title", "" )
              .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
              .autocomplete({
                delay: 0,
                minLength: 0,
                source: $.proxy( this, "_source" )
              })
              .tooltip({
                classes: {
                  "ui-tooltip": "ui-state-highlight"
                }
              });
    
            this._on( this.input, {
              autocompleteselect: function( event, ui ) {
                ui.item.option.selected = true;
                this._trigger( "select", event, {
                  item: ui.item.option
                });
              },
    
              autocompletechange: "_removeIfInvalid"
            });
          },
    
          _createShowAllButton: function() {
            var input = this.input,
              wasOpen = false;
    
            $( "<a>" )
              .attr( "tabIndex", -1 )
              .attr( "title", "Show All Items" )
              .tooltip()
              .appendTo( this.wrapper )
              .button({
                icons: {
                  primary: "ui-icon-triangle-1-s"
                },
                text: false
              })
              .removeClass( "ui-corner-all" )
              .addClass( "custom-combobox-toggle ui-corner-right" )
              .on( "mousedown", function() {
                wasOpen = input.autocomplete( "widget" ).is( ":visible" );
              })
              .on( "click", function() {
                input.trigger( "focus" );
    
                // Close if already visible
                if ( wasOpen ) {
                  return;
                }
    
                // Pass empty string as value to search for, displaying all results
                input.autocomplete( "search", "" );
              });
          },
    
          _source: function( request, response ) {
            var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
            response(this.element.children("option").map(function () {
                var text = $(this).text();
                //Here needs changes 
                //if (this.value && (!request.term || matcher.test(text)))
                if (this.value && (!request.term || matcher.test(text.split("|")[0]) ) )
                return {
                  label: text,
                  value: text,
                  option: this
                };
            }) );
          },
    
          _removeIfInvalid: function( event, ui ) {
            // Selected an item, nothing to do
            if ( ui.item ) {
              return;
            }
            // Search for a match (case-insensitive)
            var value = this.input.val(),
              valueLowerCase = value.toLowerCase(),
              valid = false;
            this.element.children( "option" ).each(function() {
              if ( $( this ).text().toLowerCase() === valueLowerCase ) {
                this.selected = valid = true;
                return false;
              }
            });
    
            // Found a match, nothing to do
            if ( valid ) {
              return;
            }
    
            // Remove invalid value
            this.input
              .val( "" )
              .attr( "title", value + " didn't match any item" )
              .tooltip( "open" );
            this.element.val( "" );
            this._delay(function() {
              this.input.tooltip( "close" ).attr( "title", "" );
            }, 2500 );
            this.input.autocomplete( "instance" ).term = "";
          },
    
          _destroy: function() {
            this.wrapper.remove();
            this.element.show();
          }
        });
    
        $( "#combobox" ).combobox();
        $( "#toggle" ).on( "click", function() {
          $( "#combobox" ).toggle();
        });
      } );
        </script>
    </head>
    <body>
    
        <div class="ui-widget">
            <label>Your preferred programming language: </label>
            @Html.DropDownList("combobox",ViewBag.CategoryListNew as IEnumerable<SelectListItem>, "--Select--")
        </div>
        <button id="toggle">Show underlying select</button>
    
    
    </body>
    </html>

    Best Regards,

    Daisy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 11, 2017 7:53 AM
  • User-366701151 posted

    @x.daizy   thanks a million times bro.

    Monday, December 11, 2017 8:34 AM