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 8138459
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T11:30:11+00:00 2026-06-06T11:30:11+00:00

Background Currently in a project of mine I am using jQuery autocomplete for a

  • 0

Background

Currently in a project of mine I am using jQuery autocomplete for a few fields.

To provide context, the application records Runs. Each Run must have a Route associated with it. A Route meaning, where the user ran.

When the user types in a Route, a list of their Routes gets displayed by the autocomplete options, but the database requires the RouteID for validation.

To compensate for this, I stored the RouteID in a HiddenFor HtmlHelper. When the user selects the route from the autocomplete, the HiddenFor gets assigned.

What my problem is

If the user types in the full name of the Route, instead of selecting it from the autocomplete list or enters a Route that does not exist, the HiddenFor will not get assigned. When this happens, I have to find the Route by its name and validate that it exists on the server.

I would like to not have to create this work-around for every autocomplete.

The bottom line

Is there anyway to make the autocomplete act more like a select list? I want the user to have no choice but to select the text of one option from the autocomplete list, and have the value of the selected option is sent to the server.

If I have to stick to the HiddenFor method, is there at least a way to force the user to select an option from the autocomplete list?


Below is the code I am currently using

Mark-up

@Html.LabelFor(model => model.RouteID, "Route")
<input type="text" data-autocomplete-url="@Url.Action("../Route/GetRoutesByUser")" />
@Html.HiddenFor(m => m.RouteID)

jQuery

  $('*[data-autocomplete-url]')
    .each(function () {
        $(this).autocomplete({
            source: $(this).data("autocomplete-url"),
            minLength: 2,
            select: function (event, ui) {
                log(ui.item.id, ui.item.name);
            }
        });
    });

Code

public ActionResult GetRoutesByUser(string term)
{
    var routeList = db.Routes.Where(r => r.Name.Contains(term))
                    .Take(5)
                    .Select(r => new { id = r.RouteID, label = r.Name, name = "RouteID"});
    return Json(routeList, JsonRequestBehavior.AllowGet);
}
  • 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-06T11:30:12+00:00Added an answer on June 6, 2026 at 11:30 am

    Alright, after a lot of fiddling around I came up with the following implementation:

    The code below is a HtmlHelper called @Html.AutocompleteWithHiddenFor. The HtmlHelper will create an input HTML element with a data-autocomplete-url property based on the controller and action passed in.

    If the input element needs a value then you can pass that in as well. A HiddenFor will be created for the Model property passed in and a ValidationMessageFor will be created for the Model as well.

    Now all I have to do is use @Html.AutocompleteWithHiddenFor, and pass in whatever expression I need with the controller and action (and possibly the value) to get the autocomplete functionality and have the ID pass to the server instead of the text.

    jQuery

    $(function () {
        function log(id, name) {
            var hidden = $('#' + name);
            hidden.attr("value", id);
        }
    
        $('*[data-autocomplete-url]')
        .each(function () {
            $(this).autocomplete({
                source: $(this).data("autocomplete-url"),
                minLength: 2,
                select: function (event, ui) {
                    log(ui.item.id, ui.item.name);
                },
                change: function (event, ui) {
                    if (!ui.item) {
                        this.value = '';
                    } else {
                        log(ui.item.id, ui.item.name);
                    }
                }
            });
        });
    });
    

    AutocompleteHelper class

    public static class AutocompleteHelper
    {
         /// <summary>
         /// Given a Model's property, a controller, and a method that belongs to that controller, 
         /// this function will create an input html element with a data-autocomplete-url property
         /// with the method the autocomplete will need to call the method. A HiddenFor will be
         /// created for the Model's property passed in, so the HiddenFor will be validated 
         /// and the html input will not.
         /// </summary>
          /// <returns></returns>
          public static MvcHtmlString AutocompleteWithHiddenFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, string controllerName, string actionName, object value = null)
          {
              // Create the URL of the Autocomplete function
              string autocompleteUrl = UrlHelper.GenerateUrl(null, actionName,
                                                           controllerName,
                                                           null,
                                                           html.RouteCollection,
                                                           html.ViewContext.RequestContext,                                                              
                                                           includeImplicitMvcValues: true);
    
               // Create the input[type='text'] html element, that does 
               // not need to be aware of the model
               String textbox = "<input type='text' data-autocomplete-url='" + autocompleteUrl + "'";
    
               // However, it might need to be have a value already populated
               if (value != null)
               {
                   textbox += "value='" + value.ToString() + "'";
               }
    
               // close out the tag
               textbox += " />";
    
               // A validation message that will fire depending on any 
               // attributes placed on the property
               MvcHtmlString valid = html.ValidationMessageFor(expression);
    
               // The HiddenFor that will bind to the ID needed rather than 
               // the text received from the Autocomplete
               MvcHtmlString hidden = html.HiddenFor(expression);
    
               string both = textbox + " " + hidden + " " + valid;
               return MvcHtmlString.Create(both);
         }
    }
    

    View

    @Html.LabelFor(model => model.RouteID, "Route")
    @Html.AutocompleteWithHiddenFor(model => model.RouteID, "Route", "GetRoutesByUser") 
    

    Or if it needs a value

    @Html.LabelFor(model => model.Route, "Route")
    @Html.AutocompleteWithHiddenFor(model => model.RouteID, "Route", "GetRoutesByUser", @Model.RouteName) 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Some background: Currently, I'm using the Coderay gem (v 0.9.7) in a Rails project
Background : I am currently using custom controls within my C# project (basic controls
I come from a CVS background. I'm currently investigating using SVN for a project.
Background Currently, I am working on a Rails application. I have different products that
I'm currently building a simple application on Gjs , which should change the background-image
I'm currently working on setting up a new project of mine and was wondering
I'm currently trying to develop a project based upon Firemonkey. I'm using Firemonkey for
Background: I'm fairly new to C# and currently working on a project intended primarily
I am currently doing a project on GWT and in the background study, I
I'm currently working on a project in which i need to play a background

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.