Reputation: 5670
I've got the functionality I need almost complete and am looking for a little help. I have a model with a VendorID property. I have a strongly typed view using this model. I allow the user to select a vendor from an input text box that uses auto complete.
I bind the model's VendorID property to a hidden field on the view with this razor syntax.
@Html.HiddenFor(m => m.VendorID)
When the user types in a few characters in to the textbox and selects an item, the jquery function I've got sets the value of the hidden field. Up to this point, everything works great. The problem I have is if the user clears the textbox completely or enters invalid text, whereas there isn't a valid value selected, and my hidden field can't be updated.
Here is my jquery I have so far.
$(document).ready(function () {
$('#vendorautocomplete').val($('#VendorName').val()); //prepopulate our vendorautocomplete textbox from our model
});
$(function () {
$('#vendorautocomplete').autocomplete({
source: function (request, response) {
$.ajax({
url: "/test/vendors", type: "POST", dataType: "json", //Url to our action supplying a list of vendors
data: { searchString: request.term, maxRecords: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.VendorName, value: item.VendorName, id: item.VendorID };
}));
}
});
},
select: function (event, ui) {
$('#VendorID').val(ui.item ? ui.item.id : 0); //Set our VendorID hidden for model binding
}
});
});
I was hoping I could do something in the Autocomplete function similar to select: above only for blur:, but that didn't work. I suppose I could use the blur event to look up the ID of the vendor based on the value in the textbox, but it seems at some point I should be able to detect the invalid vendor name and set the hidden field to 0, I just don't know where.
Upvotes: 2
Views: 2523
Reputation: 5670
I managed to accomplish what I wanted to do by adding the following to my scripts.
For bad search data (no values returned)
success: function (data) {
var arr = $.map(data, function (item) { return { label: item.VendorName, value: item.VendorName, id: item.VendorID }; });
if (arr.length == 0) {
$('#VendorID').val(null);
$('#VendorName').val('');
}
response(arr);
}
I check for a blank text box on the change event
$(function () {
$('#vendorautocomplete').change(function () {
if ($('#vendorautocomplete').val() == null || $('#vendorautocomplete').val() === "") {
$('#VendorID').val(null);
$('#VendorName').val('');
}
});
});
Not sure it's the best solutuion, but it works and I need to move onto other problems.
Upvotes: 1