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.
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" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With