JQuery UI Autocomplete with .Net MVC: how to display label when selected but keep value

I implemented Autocomplete and I am having problems with the label and value in the text box after selecting an item. When I enter the zip code, I see a shortcut in the drop-down list:

displayvalue.jpg

but after I select it, instead of the label displayed in the text box, a value is displayed (which is the identifier that needs to be stored in the database):

displayvalue2.jpg

How can I show the label after selecting it, but then when the form is saved, it passes the ZipCodeID for the field?

Here is my controller method:

public JsonResult FindZipCode(string term)
    {
        VetClinicDataContext db = new VetClinicDataContext();

        var zipCodes = from c in db.ZipCodes
                       where c.ZipCodeNum.ToString().StartsWith(term)
                       select new { value = c.ZipCodeID, label = c.ZipCodeNum};

        return this.Json(zipCodes, JsonRequestBehavior.AllowGet);
    }

And here is my markup:

<script type="text/javascript">
    $(document).ready(function() {
        $("#ZipCodeID").autocomplete({
                  source: '<%= Url.Action("FindZipCode", "Customers") %>',
        });
    });
</script>

<div class="ui-widget"><input type="text" name="ZipCodeID" id="ZipCodeID" /></div>

EDIT: Here is my last working code:

Controller:

public JsonResult FindZipCode(string term)
    {
        VetClinicDataContext db = new VetClinicDataContext();

        var zipCodes = from c in db.ZipCodes
                       where c.ZipCodeNum.ToString().StartsWith(term)
                       select new { value = c.ZipCodeID, label = c.ZipCodeNum};

        return this.Json(zipCodes, JsonRequestBehavior.AllowGet);
    }

and markup:

<script type="text/javascript">
    $(document).ready(function() {
        $("#ddZipCode").autocomplete({
            source: '<%= Url.Action("FindZipCode", "Customers") %>',
            select: function(event, ui) {
                var zipCodeID = parseInt(ui.item.value, 1);
                $("#ddZipCode").val(ui.item.label);
                $("#ZipCodeID").val(ui.item.value);
                return false;
            }
        });
    });
</script>

<div class="ui-widget"><input type="text" name="ddZipCode" id="ddZipCode" /></div>
<%= Html.Hidden("ZipCodeID")%>
+5
2

, ...

zipcode. , .

.

, , ?

+6

, , (, , , ).

select: function (event, ui) {
     event.preventDefault();
     event.target.innerText = ui.item.label;
}
+4

All Articles