Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post value from autocomplete instead of text?

This is my C# Code:

public JsonResult FillUsers(string term)
    {
        var Retailers = from us in db.Users
                        join pi in db.UserPersonalInfoes on us.ID equals pi.UserID into t
                        from rt in t.DefaultIfEmpty()
                        where us.Status == true
                        select new
                        {
                            ID = us.ID,
                            Username = us.Username + ":( " + (rt == null ? String.Empty : rt.FirstName) + " )"
                        };

        List<string> UsersList;
        UsersList = Retailers.Where(x => x.Username.Contains(term)).Select(y => y.Username).Take(10).ToList();

        return Json(UsersList, JsonRequestBehavior.AllowGet);
    }

HTML Code:

<div class="col-md-3">
                 @Html.TextBox("ddlUser", null, new { @id = "ddlUser", @class = "form-control" })
             </div>

Javascript Code:

<script type="text/javascript">
$(function () {
    $("#ddlUser").autocomplete({
        source: '@Url.Action("FillUsers", "FirebaseNotification")',
        select:function(event, ui)
        {
            var id = ui.item.ID;
            var name = ui.item.Username;
        }
        });
    });

I want show 'username' in text field but when form will be post I want to send 'ID'. Instead of that I am getting username.

like image 294
Luqman Avatar asked Nov 09 '22 02:11

Luqman


1 Answers

To achieve that you might need an additional hidden field in which you store the id when a selection is made:

$("#ddlUser").autocomplete({
    source: '@Url.Action("FillUsers", "FirebaseNotification")',
    select: function(event, ui) {
        var id = ui.item.ID;
        $('#selectedUserId').val(id);
    }
});

Now when the form is submitted you will ignore the username value coming from the text input field, but rather take the hidden field value:

@Html.Hidden("selectedUserId", null, new { id = "selectedUserId" })
like image 52
Darin Dimitrov Avatar answered Nov 14 '22 20:11

Darin Dimitrov