I getting name perfectly but I am not getting their name related ID in ajax autocomplete
Following is the view code,
#Html.TextBoxFor(model => Model.CustomerFullName, new { #class = "form-control" })
#Html.TextAreaFor(model => Model.CustomerId)
$(document).ready(function () {
$("#CustomerFullName").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("AutoComplete", "Order")',
datatype: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val) {
return {
value: val.Name,
label: val.Name
}
}))
}
})
},
select: function (event, ui) {
alert(ui.item.id);
$("#CustomerId").val(ui.item.id);
}
});
});
Here is the controller,
public JsonResult AutoComplete(string term = "")
{
var objCustomerlist = (from customer in _customerRepository.Table
where customer.Username.StartsWith(term)
select new
{
Name = customer.Username,
ID = customer.Id
}).ToList();
return Json(objCustomerlist);
}
In autocomplete ajax select section alert showing undefined
I tried things to solve like
JSON.Stringfy(ui.item.id)
ui.id
but still didnt work.
Related
I have a new project and decided to go with c# .net 6 MVC in VS2022...
In may old projects this code works flawless.
#section Scripts
{
<script type="text/javascript">
$("#Klijent_Name").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Action("SearchKlijenti")",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.label, value: item.label, id: item.id };
}))
}
})
},
minLength: 1,
select: function (event, ui) {
$("#KlijentId").val(ui.item.id);
$("#KlijentLabel").html(ui.item.label);
$("#SearchKupac").val("");
return false;
}
});
</script>
}
and latest variation of controller endpoint:
public JsonResult SearchKlijenti(string term)
{
var klijentVM = _klijent.Search(term);
if (klijentVM != null)
{
var items = klijentVM.Select(x => new { id = x.KlijentId, label = x.FriendlyName });
return new JsonResult(Ok(items));
}
return new JsonResult(Ok());
}
Using latest jQuery 3.6.1, and bootstrap 5.2.0. Tried using jquery-ui.js, jquery.unobtrusive-ajax.js...
Problem is that the call is not triggered, or not finding it's way to controller action. Have tried putting alert(); and omitting data manipulation and calls, but still nothing. When testing jQuery:
$("SearchKupac").keyup(function() {
alert();
});
works.
Tried to debug using Firefox, but either I don't know to use it, or the call is not triggered.
I don't know where and what to look anymore...
EDIT: Here is also HTML snippet
<label asp-for="Klijent.Name">Ime</label>
<input class="form-control ajax" asp-for="Klijent.Name" />
<span asp-validation-for="Klijent.Name" class="text-danger"></span>
I also tried selecting with $("input.ajax")... Tried double and single quotes. Bare in mind, this is a working code from MVC 5 project. It doesn't work in new project
If you want to use keyup event,here is a demo:
<input id="SearchKupac" />
js:
$("#SearchKupac").keyup(function() {
alert();
});
If the id of input is SearchKupac,you need to use $("#SearchKupac") in js.Also,you can use $("#SearchKupac") with autocomplete.
#section Scripts
{
<script type="text/javascript">
$("#SearchKupac").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Action("SearchKlijenti")",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.label, value: item.label, id: item.id };
}))
}
})
},
minLength: 1,
select: function (event, ui) {
$("#KlijentId").val(ui.item.id);
$("#KlijentLabel").html(ui.item.label);
$("#SearchKupac").val("");
return false;
}
});
</script>
}
So Firefox developer tool was of no help. Crome developer tool find an error. It was not apparent immediately, but the jquery-ui.js (of version 1.13.2 in my case) resolved the issue.
<script src="~/js/jquery-ui-1.13.2/jquery-ui.min.js"></script>
There was also an issue in controller. it has to be of type JsonResult and return Json(items) not Json(Ok(items))
public JsonResult SearchKlijenti(string term)
{
var klijentVM = _klijent.Search(term);
if (klijentVM != null)
{
var items = klijentVM.Select(x => new
{
id = x.KlijentId,
name = string.IsNullOrEmpty(x.Name) ? " " : x.Name,
friendly = string.IsNullOrEmpty(x.FriendlyName) ? " " : x.FriendlyName,
person = string.IsNullOrEmpty(x.PersonName) ? " " : x.PersonName,
tel = string.IsNullOrEmpty(x.Contact) ? " " : x.Contact,
mail = string.IsNullOrEmpty(x.Mail) ? " " : x.Mail,
oib = string.IsNullOrEmpty(x.OIB) ? " " : x.OIB,
adresa = string.IsNullOrEmpty(x.Adress) ? " " : x.Adress,
});
return Json(items);
}
return Json(null);
}
And for completeness, here is my script:
#section Scripts
{
<script type="text/javascript">
$("input.ajax").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Action("SearchKlijenti")",
type: "GET",
dataType: "json",
data: { term: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.friendly,
value: item.friendly,
id: item.id,
name: item.name,
friendly: item.friendly,
person: item.person,
tel: item.tel,
mail: item.mail,
oib: item.oib,
adresa: item.adresa
};
}))
}
})
},
minLength: 1,
select: function (event, ui) {
$("#Klijent_KlijentId").val(ui.item.id);
$("#Klijent_KlijentName").val(ui.item.name)
$("#Klijent_FriendlyName").val(ui.item.label)
$("#Klijent_OIB").val(ui.item.oib)
$("#Klijent_PersonName").val(ui.item.person)
$("#Klijent_Contact").val(ui.item.tel)
$("#Klijent_Mail").val(ui.item.mail)
$("#Klijent_Adress").val(ui.item.adresa)
return false;
}
})
</script>
}
Did not yet test return Json(null), but that is not part of this exercise :)
I am getting autocomplete item list from javascript autocomplete but when I select that autocomplete item list at that time it shows the error i.e. Uncaught TypeError: n.item is undefined
Here is my code,
<div class="form-group">
<div class="col-md-3">
<nop-label asp-for="Name" />
</div>
<div class="col-md-9">
#Html.TextBoxFor(model => Model.Name, new { #class = "form-control" })
#Html.HiddenFor(model => Model.Name)
</div>
</div>
$(document).ready(function () {
$("#Name").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("AutoComplete", "Product")',
datatype: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val) {
return {
label: val.Name,
value: val.Name
}
}))
}
})
},
select: function (ui) {
$("#Name").val(ui.item.Name);
}
});
});
Here is the controller
public JsonResult AutoComplete(string term = "")
{
var objCustomerlist = (from product in _productMasterRepository.Table
where product.Name.StartsWith(term)
select new
{
Name = product.Name,
ID = product.Name
}).ToList();
return Json(objCustomerlist);
}
Your select signature is incorrect:
select: function (ui) {
$("#Name").val(ui.item.Name);
}
Change it into:
select: function (event, ui) {
$("#Name").val(ui.item.Name);
}
And that should work fine.
I have one field in my view, it is a textbox field. But I'd like to change that field to an Autocomplete dropdown.
Below is my view:
#Html.TextBoxFor(model => model.SearchFilterPaymentCode, new { #class = "form-control", #id = "searchInput1" })
#Html.HiddenFor(model => model.ID)
<script>
$(document).ready(function () {
$("#searchInput1").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("getJenisPembayaran", "Payment1")',
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val.Name,
value: val.Name,
ID: val.ID
}
}))
}
})
},
select: function (event, ui) {
$("#ID").val(ui.item.ID);
$("#SearchFilterPaymentCode").val(ui.item.label);
}
});
})
</script>
and below is my controller
public JsonResult getJenisPembayaran(string term)
{
var objCustomerlist = db.ParamJenisPembayarans.Where(x => x.Name.ToUpper()
.Contains(term.ToUpper()))
.Select(x => new ParamJenisPembayaranViewModel
{
ID = x.ID,
JenisPembayaran = x.Name
}).Distinct().ToList();
return Json(objCustomerlist, JsonRequestBehavior.AllowGet);
}
When I debug the controller and fill the textbox with a few words, I get some data from the database, that means the controller is working well but the data does not appear in the view. What's wrong with my code?
I have my textboxfor field which select the data from role table from the database
i need this textboxfor field make a autocomplete with starting character.
Sample:
MVC code:
This JsonResult in the UsersControl
public JsonResult GetRoles(string Prefix)
{
var RoleListVal = db.Roles.Where(r => r.Deleted == false)
.Where(r => r.Name.ToUpper().StartsWith(Prefix))
.Select(r => new { Name = r.Name, ID = r.RoleID }).Distinct().ToList();
return Json(RoleListVal, JsonRequestBehavior.AllowGet);
}
cshtml Code:
This the JS and the HTML5 TextBoxFor:
$("#keywords-manual").autocomplete({
source: "/Users/GetRoles",
minLength: 1
})
<div class="form-inline">
#Html.Label("Role :")
#Html.TextBoxFor(model => model.Roles.FirstOrDefault().Name, new { #class = "form-control", #id = "keywords-manual" })
</div>
I don't why isn't working!
Here your controller side method looks good.
But issue is while you calling method.
$("#keywords-manual").autocomplete({
source: function (request, response) {
$.ajax(
{
type: "POST",
url: '#Url.Action("GetRoles","Users")',
data: { Prefix: $('#keywords-manual').val() },
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
return {
value: item.Name,
description: item
}
}))
},
error: function (error) {
console.log(error);
}
});
},
minLength: 1,
select: function (event, ui) {
}
});
This is how you configure the Autocomplete plug in
On HTML Side:
$(function () {
$("#keywords-manual").autocomplete({
source: "#Url.Action("GetRoles","Users")",
minLength: 1
})
});
On the controller side:
public JsonResult GetRoles(string term)
{
var RoleListVal = db.Roles.Where(r => r.Deleted == false)
.Where(r => r.Name.ToUpper().StartsWith(term))
.Select(r => new { label = r.Name, id = r.RoleID,value=r.RoleID }).Distinct().ToList();
return Json(RoleListVal, JsonRequestBehavior.AllowGet);
}
I am passing complex JSON data to jQuery autocomplete plugin. And it is working fine so it shows the list of Products.
Now I want to get somehow Price that is already included into JSON data and when I select product from autocomlete list I would like to populate input tag with Price.
I really cannot get if it is possible to do. What I know that data is already in JSON but how to get it?
Any clue?
Here is JS for jQuery autocomplete plugin
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
}
});
});
}
To make clear item.LastPrice has Price data.
And HTML
#Html.AutocompleteFor(x => x.ProductUID, Url.Action("AutocompleteProducts", "Requisition"), true, "Start typing Product name...", Model.Product.Name)
In your ui.item object you should be able to find the the Price property in there and then set the value in the select function.
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
price: item.LastPrice // you might need to return the LastPrice here if it's not available in the ui object in the select function
};
}));
},
..
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name'),
unitPriceEl = $('#price');
$('#' + hiddenFieldName).val(ui.item.UID);
unitPriceEl.val(ui.item.LastPrice); //set the price here
}
Thanks to dcodesmith!!! I am gonna mark his solution like an answer but just in case I will share my final code that is working fine now.
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
lastPrice: item.LastPrice
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
var unitPriceEl = $('#UnitPrice');
unitPriceEl.val(ui.item.lastPrice);
console.log(ui.item.lastPrice);
}
});
});
}