I'm binding an AutoComplete to data server-side and it may, conditionally, already have a value set. I want to make sure that the user cannot add values that are not in the list so I've added a script that searches the dataSource for the value before the form is submitted. The problem seems to be when the textbox is given a value server-side, so it's never typed in or searched client-side before submitting, the dataSource .view() and .data() are empty (so it thinks my text is invalid). How can I get my dataSource to include the data without the user typing in the textbox?
01.
@(Html.Kendo().AutoComplete()
02.
.Name(
"ac-selected-gym"
)
03.
.BindTo(Model.AvailableLocations)
04.
.DataTextField(
"GymName"
)
05.
.Filter(
"contains"
)
06.
.MinLength(1)
07.
.HtmlAttributes(
new
{ @
class
=
"form-control"
, data_selected_gym =
""
, aria_describedby =
"selectedGymHelp"
})
08.
.Placeholder(
"Select your gym"
)
09.
.Value(Model.AvailableLocations.Where(f => f.Id== Model.SelectedId).FirstOrDefault()?.GymName)
10.
.Events(e => e.Change(
"sso.saml2.onGymChange"
))
11.
)
01.
function
getSelectedGym($flnAc) {
02.
var
selectedGym;
03.
04.
var
value = $flnAc.value();
05.
var
gymData = $flnAc.dataSource.view();
//This actually appears to return only the current match (or nothing)
06.
07.
var
searchSource =
function
(dataSource, gymName) {
08.
var
matchedGym;
09.
for
(
var
x = 0, length = dataSource.length; x < length; x++) {
10.
if
(dataSource[x].GymName === gymName) {
11.
matchedGym = dataSource[x];
12.
break
;
13.
}
14.
}
15.
return
matchedGym;
16.
};
17.
18.
selectedGym = searchSource(gymData, value);
19.
20.
//dataSource.view() may not have our item in it e.g. if the textbox was pre-filled server-side rather
21.
//than typed client-side, so search the whole list if not found. (Couldn't find a way to tell the control to update its datasource)
22.
if
(!selectedGym) {
23.
gymData = $flnAc.dataSource.data();
24.
selectedGym = searchSource(gymData, value);
25.
}
26.
27.
return
selectedGym;
28.
}
As you can see I tried to work around .view() being empty but then found that .data() is also empty. I also tried triggering the change event on load, but it was still empty.