john
john

Reputation: 1567

MVC Razor Autocomplete Text box with dropdown result

I have a textbox that I need for users to start typing in. As they type I need to display the results in a dropdown list under the textbox. Once the user selects the item they want, then I need it to appear in the textbox. The list of items is pulled from the controller. This is an MVC page using razor pages. The controller is already in place, I just need to know how to wire this up. I am more of a middle/back end developer so this is new territory for me. If someone can point me to a site, code, or example that does this, I can figure it out from there.

Thanks

Upvotes: 2

Views: 8360

Answers (2)

Dans
Dans

Reputation: 226

If you wont use third parts

Controller:

public JsonResult MyData(string text)
{
    text = text.ToLower().Trim();
    string[] words = { "Microsoft", "Microsoft MVC", "Google", "Apple" };

    IEnumerable<string> matched = words.Where(x => x.ToLower().StartsWith(text));

    return Json(matched, JsonRequestBehavior.AllowGet);
}

View:

<input id="search" type="text">
<br>
<select id="result" multiple></select>

@section scripts{
<script>
    $("#search").on("keypress", function () {
        // get the value ftom input
        var text = $(this).val();

         if (text.length > 0)
        {
            $.get("@Url.Action("MyData")", { text: text }, function (data) {

                //add all data
                for (i = 0; i < data.length; i++)
                {
                    $("#result").append('<option>' + data[i] + "</option>");
                }

                //if hidden show the select
                if ($("#result").is(":hidden"))
                {
                    $("#result").show();
                }
            });
        }
    });

    $(document).on("click", "#result > option", function () {

        //add selected value to #search
        $("#search").val($(this).val());

        //clear and hide #result
        $("#result").empty().hide();
    });
</script>
}

Have fun ;)

Upvotes: 2

Antony Samy Joseph
Antony Samy Joseph

Reputation: 92

You can create a auto complete textbox with help of jQueryUI autocomplete plugin. For datasource, you can create apicontroller and provide data for autocomplete textbox.

For eg:

Api Controller:

[Produces("application/json")]
[Route("api/Home")]
public class HomeController : Controller
{       
        [Route("")]        
        public IActionResult Index()
        {        
            return Ok(new List<string> { "test", "test2" });
        }
}

Page.cshtml:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<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 type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            url: "/api/Home",
            type: "GET",            
            success: function (data) {
                $('#AutoCc').autocomplete({
                       source: data
                });
            },
            error: function (error) {                
            }
       })
    })
</script>


<input id="AutoCc" type="text" name="AutoCc" />

Upvotes: 0

Related Questions