How to post a 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 to show "username" in the text box, but when the form is submitted, I want to send "ID". Instead, I get the username.

+5
source share
2 answers

To do this, you may need an additional hidden field in which you store the identifier when you select:

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

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

 @Html.Hidden("selectedUserId", null, new { id = "selectedUserId" }) 
0
source

 $("#ddlUser").keyup(function (e) { if (e.which != 13) { $("#hfUserID").val("0"); } $("#ddlUser").autocomplete({ source: function (request, response) { ... }, select: function (e, i) { $("#hfUserID").val(i.item.val); $("#ddlUser").val(i.item.label); }, minLength: 1 }); }); 
0
source

Source: https://habr.com/ru/post/1263239/


All Articles