Trying to use a jquery-ui combobox in asp.net webforms - asp.net

I'm trying to use the jqueryUI combobox into my asp.net 3.5 webforms application. I've added a dropdownlist and modified it style with jquery. The problem i got is when i try to execute the postback the dropdown normally does when it selected item it's changed. The combobox doesn't change it's value and I'm getting the error that _dopostback is not defined in my firebug error console. I've been reading about this here and in and in in the asp.net forums, and found some answers that told me that should give a try to the GetPostBackEventReference method, but still nothing has happened. Below is the code, thanks.
<script type="text/javascript">
(function ($) {
$.widget("ui.combobox", {
_create: function () {
var input,
self = this,
select = this.element.hide(),
selected = select.children(":selected"),
value = selected.val() ? selected.text() : "",
wrapper = $("<span>")
.addClass("ui-combobox")
.insertAfter(select);
input = $("<input>")
.appendTo(wrapper)
.val(value)
.addClass("ui-state-default")
.autocomplete({
delay: 0,
minLength: 0,
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(select.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}));
},
select: function (event, ui) {
ui.item.option.selected = true;
self._trigger("selected", event, {
item: ui.item.option
});
_doPostBack('<%= ddlModalities.UniqueID %>', "");
},
change: function (event, ui) {
if (!ui.item) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
select.children("option").each(function () {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
$(select).change();
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
$(this).val("");
select.val("");
input.data("autocomplete").term = "";
return false;
}
}
}
})
.addClass("ui-widget ui-widget-content ui-corner-left");
input.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
$("<a>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.appendTo(wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function () {
// close if already visible
if (input.autocomplete("widget").is(":visible")) {
input.autocomplete("close");
return;
}
// work around a bug (likely same cause as #5265)
$(this).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
input.focus();
});
},
destroy: function () {
this.wrapper.remove();
this.element.show();
$.Widget.prototype.destroy.call(this);
}
});
})(jQuery);
$(function () {
$("#<%=ddlModalities.ClientID %>").combobox();
});
</script>
<div class="ui-widget">
<asp:DropDownList runat="server" ID="ddlModalities" Width="150px" AutoPostBack="True"
DataSourceID="odsModalitiesNoWorklist" DataTextField="Ae" DataValueField="Id"
CssClass="ddlStandardWidth" OnDataBound="ddlModalities_DataBound" OnSelectedIndexChanged="ddlModalities_SelectedIndexChanged" />
</div>

It looks like you're calling "_doPostBack". However, the ASP.NET-generated function is "__doPostBack" - there are two "_" characters at the beginning, not just one. That could be the cause of your "function not defined" error.

Related

Stop x-tags from capturing focus/blur events

I am trying to create a custom element which wraps tinyMCE functionality.
I have the following:-
(function(xtag) {
xtag.register('x-tinymce', {
lifecycle:{
created: tinymceCreate,
removed: tinymceDestroy
},
accessors: {
disabled: {
attribute: {
boolean: true
},
get: getDisabledAttribute,
set: setDisabledAttribute
}
}
});
function tinymceCreate(){
var textarea = document.createElement('textarea');
var currentElement = this;
currentElement.textAreaId = xtag.uid();
textarea.id = currentElement.textAreaId;
currentElement.appendChild(textarea);
currentElement.currentMode = 'design';
var complexConfig = {
selector: '#' + currentElement.textAreaId,
setup: editorSetup
}
tinymce.init(complexConfig)
.then(function thenRetrieveEditor(editors) {
currentElement.currentEditor = editors[0];
currentElement.currentEditor.setMode(currentElement.currentMode ? currentElement.currentMode : 'design');
});
function editorSetup(editor) {
editor.on('blur', function blur(event) {
editor.save();
document.getElementById(editor.id).blur();
xtag.fireEvent(currentElement, 'blur', { detail: event, bubbles: false, cancellable: true });
});
editor.on('focus', function focus(event) {
xtag.fireEvent(currentElement, 'focus', { detail: event, bubbles: false, cancellable: true });
});
editor.on('BeforeSetContent', function beforeSetContent(ed) {
if (ed.content)
ed.content = ed.content.replace(/\t/ig, ' ');
});
}
}
function tinymceDestroy() {
if (this.currentEditor)
tinymce.remove(this.currentEditor);
}
function getDisabledAttribute() {
return this.currentMode === 'readonly';
}
function setDisabledAttribute(value) {
if (value) {
this.currentMode = 'readonly';
}
else {
this.currentMode = 'design';
}
if (this.currentEditor) {
this.currentEditor.setMode(this.currentMode);
}
}
})(xtag);
Now, when I register a blur event, it does get called, but so does the focus event. I think that this is because focus/blur events are captured by x-tag by default. I don't want it to do that. Instead, I want these events fired when the user focusses/blurs tinymce.
I am using xtags 1.5.11 and tinymce 4.4.3.
Update 1
OK, the problem is when I call:-
xtag.fireEvent(currentElement, 'focus', { detail: event, bubbles: false, cancellable: true });
This caused the focus to be lost on the editor and go to the containing eleemnt (x-tinymce). To counter this, I modified my editorSetup to look like this:-
function editorSetup(editor) {
// // Backspace is not detected in keypress, so need to include keyup event as well.
// editor.on('keypress change keyup focus', function(ed) {
// $j("#" + editor.id).trigger(ed.type);
// });
var isFocusFromEditor = false;
var isBlurFromEditor = false;
editor.on('blur', function blurEvent(event) {
console.log("blurred editor");
if (!isFocusFromEditor) {
editor.save();
xtag.fireEvent(currentElement, 'blur', { detail: event, bubbles: false, cancellable: false });
}
else {
console.log('refocussing');
isFocusFromEditor = false;
editor.focus();
isBlurFromEditor = true;
}
});
editor.on('focus', function focusEvent(event) {
console.log("Focus triggered");
isFocusFromEditor = true;
xtag.fireEvent(currentElement, 'focus', { detail: event, bubbles: false, cancellable: false });
});
editor.on('BeforeSetContent', function beforeSetContent(ed) {
if (ed.content) {
ed.content = ed.content.replace(/\t/ig, ' ');
}
});
}
This stops the blur event from triggering, unfortuantely, now, the blur event does not get called when you leave the editing area.
This feels like a tinyMCE problem, just not sure what.
Here is a solution that catches focus and blur events at the custom element level.
It uses the event.stopImmediatePropagation() method to stop the transmission of the blur event to other (external) event listeners when needed.
Also, it uses 2 hidden <input> (#FI and #FO) controls in order to catch the focus when the tab key is pressed.
document.registerElement('x-tinymce', {
prototype: Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
var textarea = this.querySelector('textarea')
var output = this.querySelector('output')
output.textContent = "state"
var self = this
self.textAreaId = this.dataset.id // xtag.uid();
textarea.id = self.textAreaId
var complexConfig = {
selector: '#' + self.textAreaId,
setup: editorSetup,
}
var FI = this.querySelector('#FI')
FI.addEventListener('focus', function(ev) {
if (ev.relatedTarget) {
var ev = new FocusEvent('focus')
self.dispatchEvent(ev)
} else {
var ev = new FocusEvent('blur')
self.dispatchEvent(ev)
focusNextElement(-1)
}
})
var FO = this.querySelector('#FO')
FO.addEventListener('focus', function(ev) {
if (!ev.relatedTarget) {
var ev = new FocusEvent('blur')
self.dispatchEvent(ev)
focusNextElement(1)
} else {
var ev = new FocusEvent('focus')
self.dispatchEvent(ev)
}
})
var focused = false
this.addEventListener('focus', function(ev) {
console.log('{focus} in ', this.localName)
if (!focused) {
focused = true
output.textContent = focused
self.editor.focus()
} else {
console.error('should not be here')
ev.stopImmediatePropagation()
}
})
this.addEventListener('blur', function(ev) {
console.log('{blur} in %s', this.localName)
if (focused) {
focused = false
output.textContent = focused
} else {
console.log('=> cancel blur')
ev.stopImmediatePropagation()
}
})
tinymce.init(complexConfig).then(function(editors) {
//self.currentEditor = editors[0]
})
//private
function focusNextElement(diff) {
//add all elements we want to include in our selection
var focussableElements = 'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])'
if (document.activeElement) {
var focussable = Array.prototype.filter.call(document.querySelectorAll(focussableElements), function(element) {
//check for visibility while always include the current activeElement
return element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement
})
var index = focussable.indexOf(document.activeElement)
focussable[index + diff].focus()
}
}
function editorSetup(editor) {
console.warn('editor setup')
self.editor = editor
editor.on('focus', function(event) {
if (!focused) {
var ev = new FocusEvent('focus')
self.dispatchEvent(ev)
}
})
editor.on('blur', function(event) {
//if ( focused )
{
var ev = new FocusEvent('blur')
self.dispatchEvent(ev)
}
})
}
}
},
detachedCallback: {
value: function() {
if (this.editor)
tinymce.remove(this.editor)
}
}
})
})
var xElem = document.querySelector('x-tinymce')
xElem.addEventListener('focus', function(ev) {
console.info('focus!')
})
xElem.addEventListener('blur', function(ev) {
console.info('blur!')
})
<script src="http://cdn.tinymce.com/4/tinymce.min.js"></script>
<input type="text">
<x-tinymce data-id="foo">
<output id=output></output>
<input type=text id=FI style='width:0;height:0;border:none'>
<textarea>content</textarea>
<input type=text id=FO style='width:0;height:0;border:none'>
</x-tinymce>
<input type="text">

Google Places Autocomplete, simulate first result selection on button click

I'm using Google Places Autocomplete and Google Maps api.
In my js I wrapped the listener for the autocomplete in order to simulate a combination of "down arrow" and "enter" events if there is no autocomplete result selected.
See the following snippet:
var pac_input = document.getElementById('locatorPlaceSearch');
var orig_listener;
(function pacSelectFirst(input) {
// store the original event binding function
var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;
function addEventListenerWrapper(type, listener) {
// Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected,
// and then trigger the original listener.
if (type == "keydown") {
orig_listener = listener;
listener = function (event) {
var suggestion_selected = $(".pac-item-selected").length > 0;
if (event.which == 13 && !suggestion_selected) {
var simulated_downarrow = $.Event("keydown", {
keyCode: 40,
which: 40
});
orig_listener.apply(input, [simulated_downarrow]);
}
orig_listener.apply(input, [event]);
};
}
_addEventListener.apply(input, [type, listener]);
mapsListener = listener;
}
input.addEventListener = addEventListenerWrapper;
input.attachEvent = addEventListenerWrapper;
})(pac_input);
autocomplete = new google.maps.places.Autocomplete(pac_input,
{
componentRestrictions: { country: $('#hdnLocatorPlace').val() },
types: ['geocode']
});
Now I have a "Search" button, and I want to trigger a "down arrow" and "enter" as well. I tried this code but it's not firing the keydown event on the listener:
$('#searchAP').off('click').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
setTimeout(function() {
$('#locatorPlaceSearch').focus();
$('#locatorPlaceSearch').click();
setTimeout(function() {
var sev = $.Event("keydown", {
keyCode: 13,
which: 13
});
//mapsListener.apply($('#locatorPlaceSearch'), [sev]);
$('#locatorPlaceSearch').trigger(sev);
},1000);
}, 1000);
//$('#locatorPlaceSearch').trigger(sev);
});
What's wrong with this code?
I can't tell you exactly what's going on there, as it seems the event will not be triggered at all(at least your listener will not be called).
You may trigger the event by using the native DOM-method (dispatchEvent):
google.maps.event.addDomListener(window, 'load', function() {
var pac_input = document.getElementById('locatorPlaceSearch');
var orig_listener;
(function pacSelectFirst(input) {
// store the original event binding function
var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;
function addEventListenerWrapper(type, listener) {
// Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected,
// and then trigger the original listener.
if (type == "keydown") {
orig_listener = listener;
listener = function(event) {
var suggestion_selected = $(".pac-item-selected").length > 0;
if (event.which == 13 && !suggestion_selected) {
var simulated_downarrow = $.Event("keydown", {
keyCode: 40,
which: 40
});
orig_listener.apply(input, [simulated_downarrow]);
}
orig_listener.apply(input, [event]);
};
}
_addEventListener.apply(input, [type, listener]);
mapsListener = listener;
}
input.addEventListener = addEventListenerWrapper;
input.attachEvent = addEventListenerWrapper;
})(pac_input);
autocomplete = new google.maps.places.Autocomplete(pac_input, {
componentRestrictions: {
country: $('#hdnLocatorPlace').val()
},
types: ['geocode']
});
$('#searchAP').off('click').on('click', function(e) {
var keydown = document.createEvent('HTMLEvents');
keydown.initEvent("keydown", true, false);
Object.defineProperty(keydown, 'keyCode', {
get: function() {
return 13;
}
});
Object.defineProperty(keydown, 'which', {
get: function() {
return 13;
}
});
pac_input.dispatchEvent(keydown);
});
});
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places"></script>
<input id="locatorPlaceSearch">
<input type="submit" id="searchAP">
<input type="hidden" id="hdnLocatorPlace" value="de">
Another solution, using the event-wrapper of the maps-API:
google.maps.event.addDomListener(window, 'load', function() {
(function(input, opts, nodes) {
var ac = new google.maps.places.Autocomplete(input, opts);
google.maps.event.addDomListener(input, 'keydown', function(e) {
if (e.keyCode === 13 && !e.triggered) {
google.maps.event.trigger(this, 'keydown', {
keyCode: 40
})
google.maps.event.trigger(this, 'keydown', {
keyCode: 13,
triggered: true
})
}
});
for (var n = 0; n < nodes.length; ++n) {
google.maps.event.addDomListener(nodes[n].n, nodes[n].e, function(e) {
google.maps.event.trigger(input, 'keydown', {
keyCode: 13
})
});
}
}
(
document.getElementById('locatorPlaceSearch'), {
componentRestrictions: {
country: document.getElementById('hdnLocatorPlace').value
},
types: ['geocode']
}, [{
n: document.getElementById('searchAP'),
e: 'click'
}]
));
});
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places"></script>
<input id="locatorPlaceSearch">
<input type="submit" id="searchAP">
<input type="hidden" id="hdnLocatorPlace" value="de">

MeteorJS: Collection.find fires multiple times instead of once

I have an app that when you select an industry from a drop down list a collection is updated where the attribute equals the selected industry.
JavaScript:
Template.selector.events({
'click div.select-block ul.dropdown-menu li': function(e) {
var selectedIndex = $(e.currentTarget).attr("rel");
var val = $('select#industryPicker option:eq(' + selectedIndex + ')').attr('value');
var oldVal = Session.get('currentIndustryOnet');
if(val != oldVal) {
Session.set('jobsLoaded', false);
Session.set('currentIndustryOnet', val);
Meteor.call('countByOnet', val, function(error, results){
if(results > 0) {
Session.set('jobsLoaded', true);
} else {
getJobsByIndustry(val);
}
});
}
}
});
var getJobsByIndustry = function(onet) {
if(typeof(onet) === "undefined")
alert("Must include an Onet code");
var params = "onet=" + onet + "&cn=100&rs=1&re=500";
return getJobs(params, onet);
}
var getJobs = function(params, onet) {
Meteor.call('retrieveJobs', params, function(error, results){
$('job', results.content).each(function(){
var jvid = $(this).find('jvid').text();
var job = Jobs.findOne({jvid: jvid});
if(!job) {
options = {}
options.title = $(this).find('title').text();
options.company = $(this).find('company').text();
options.address = $(this).find('location').text();
options.jvid = jvid;
options.onet = onet;
options.url = $(this).find('url').text();
options.dateacquired = $(this).find('dateacquired').text();
var id = createJob(options);
console.log("Job Created: " + id);
}
});
Session.set('jobsLoaded', true);
});
}
Template.list.events({
'click div.select-block ul.dropdown-menu li': function(e){
var selectedIndex = $(e.currentTarget).attr("rel");
var val = $('select#perPage option:eq(' + selectedIndex + ')').attr('value');
var oldVal = Session.get('perPage');
if(val != oldVal) {
Session.set('perPage', val);
Pagination.perPage(val);
}
}
});
Template.list.jobs = function() {
var jobs;
if(Session.get('currentIndustryOnet')) {
jobs = Jobs.find({onet: Session.get('currentIndustryOnet')}).fetch();
var addresses = _.chain(jobs)
.countBy('address')
.pairs()
.sortBy(function(j) {return -j[1];})
.map(function(j) {return j[0];})
.first(100)
.value();
gmaps.clearMap();
$.each(_.uniq(addresses), function(k, v){
var addr = v.split(', ');
Meteor.call('getCity', addr[0].toUpperCase(), addr[1], function(error, city){
if(city) {
var opts = {};
opts.lng = city.loc[1];
opts.lat = city.loc[0];
opts.population = city.pop;
gmaps.addMarker(opts);
}
});
})
return Pagination.collection(jobs);
} else {
jobs = Jobs.find()
Session.set('jobCount', jobs.count());
return Pagination.collection(jobs.fetch());
}
}
In Template.list.jobs if you console.log(addresses), it is called 4 different times. The browser console looks like this:
(2) 100
(2) 100
Any reason why this would fire multiple times?
As #musically_ut said it might be because of your session data.
Basically you must make the difference between reactive datasources and non reactive datasources.
Non reactive are standard javascript, nothing fancy.
The reactive ones however are monitored by Meteor and when one is updated (insert, update, delete, you name it), Meteor is going to execute again all parts which uses this datasource. Default reactive datasources are: collections and sessions. You can also create yours.
So when you update your session attribute, it is going to execute again all helper's methods which are using this datasource.
About the rendering, pages were rendered again in Meteor < 0.8, now with Blaze it is not the case anymore.
Here is a quick example for a better understanding:
The template first
<head>
<title>test</title>
</head>
<body>
{{> hello}}
</body>
<template name="hello">
<h1>{{getSession}}</h1>
<h1>{{getNonReactiveSession}}</h1>
<h1>{{getCollection}}</h1>
<input type="button" name="session" value="Session" />
<input type="button" name="collection" value="Collection" />
</template>
And the client code
if (Meteor.isClient) {
CollectionWhatever = new Meteor.Collection;
Template.hello.events({
'click input[name="session"]': function () {
Session.set('date', new Date());
},
'click input[name="collection"]': function () {
CollectionWhatever.insert({});
}
});
Template.hello.getSession = function () {
console.log('getSession');
return Session.get('date');
};
Template.hello.getNonReactiveSession = function () {
console.log('getNonReactiveSession');
var sessionVal = null;
new Deps.nonreactive(function () {
sessionVal = Session.get('date');
});
return sessionVal;
};
Template.hello.getCollection = function () {
console.log('getCollection');
return CollectionWhatever.find().count();
};
Template.hello.rendered = function () {
console.log('rendered');
}
}
If you click on a button it is going to update a datasource and the helper method which is using this datasource will be executed again.
Except for the non reactive session, with Deps.nonreactive you can make Meteor ignore the updates.
Do not hesitate to add logs to your app!
You can read:
Reactivity
Dependencies

Best way to load css for partial views loaded using ajax

I'm working on my application that creates tabs dynamically and fills them with partial views using ajax.
My question is: how to load css for this views? What's the best way to do it? I mean I can't load the css file on the partial view (no head) or could i?
Some code: the tabManager (a partial view loaded on the main page):
<script>
var tabTemplate = "<li class='#{color}'><a id='#{id}'href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>"; // base format for the tabs
$(document).ready(function () {
var tabs = $("#tabs").tabs(); // apply jQuery ui to tabs
$("a.menuButton").click(function () {
var urlContent = $(this).data("direction");
var label = $(this).data("label");
var idTab = $(this).data("id");
var color = $(this).data("color");
var exist = false;
var counter = 0;
$('#tabs ul li a').each(function (i) { // tab already exist o no hay que crear una tabla?
counter = counter + 1; // index counter
if (this.id == "#" + idTab) { // Tab already exist?
exist = true;
$("#tabs").tabs("option", "active", counter - 1); //activate existing element
}
});
if (idTab == "-1") { // is a clickable element?
exist = true;
}
if (exist == false) { // create new tab
addTab(idTab, label, color); // basic tab
getTabContent(idTab, urlContent); // content for new tab
var lastTab = $('#tabs >ul >li').size() - 1; // get count of tabs
$("#tabs").tabs("option", "active", lastTab); // select last created tab
}
});
function getTabContent(idT, urlC) { // ajax call to partial view
$.ajax({
url: urlC,
type: 'GET',
async: false,
success: function (result) {
$("#"+idT).html(result);
}
});
};
function addTab(idT, labT, color) { //create new tab
var label = labT,
id = idT,
li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label).replace(/#\{id\}/g, "#" + id).replace(/#\{color\}/g, color)),
tabContentHtml = "Cargando...";
tabs.find(".ui-tabs-nav").append(li);
tabs.append("<div id='" + id + "'><p>" + tabContentHtml + "</p></div>");
tabs.tabs("refresh");
}
// close icon: removing the tab on click
tabs.delegate("span.ui-icon-close", "click", function () {
var panelId = $(this).closest("li").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
});
tabs.bind("keyup", function (event) {
if (event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE) {
var panelId = tabs.find(".ui-tabs-active").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
}
});
});
</script>
<div id=tabs>
<ul>
</ul>
A button example:
<li><a class="menuButton" href="#" title="Permisos" data-id="tab3" data-direction="Permiso/_Administrar" data-label="Label" data-color="blue"><img src="#Res_icons.More">Permisos</a><li>
i found my answer here: http://dean.resplace.net/blog/2012/09/jquery-load-css-with-ajax-all-browsers/
the code:
<script type="text/javascript">
$(document).ready(function () {
$("head").append("<link href='...' rel='stylesheet'>");
});
</script>

Write ClientSide code from Custom ASP .NET Extender server side ExtenderControlBase

I'm extending ExtenderControlBase control in ASP .NET. It's called:
public class LookupExtender : ExtenderControlBase
Basically what it doest in something similar to autocomplete function - but static. LookupExtender has TypeName & ListName attritbutes that specify:
class that has string[] GetList(string listName) method
name of the list that will be passed to GetList method
And now, LookupExtender creates TypeName instance on the fly (reflection), calls GetList method and I would like to render string[] result to client side as array, so that extender client-side code has static source for autosuggestion.
Is there any way to render JavaScript from LookupExtender class?
This is my sample code (currently autosuggestion values are hardcoded):
set_TargetTextBoxID: function (value) {
this._targetTextBoxID = value;
$(function () {
var availableTags = [
"Switzerland",
"Poland",
"Europe",
"USA",
"Asia"
];
$("#" + value).autocomplete({
source: availableTags,
minLength: 0,
close: function () {
$(this).blur();
}
}).focus(function () {
$(this).autocomplete("search", "");
});
});
}
Turned out to be pretty easy
server side of extender:
protected override void RenderInnerScript(ScriptBehaviorDescriptor descriptor)
{
var listSource = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(SourceType) as ILookupExtenderListSource;
if (listSource == null) return;
var lookupList = listSource.GetList(SourceList);
descriptor.AddProperty("LookupArray", lookupList);
}
client side js script:
CIPNet.Extenders.LookupBehavior.prototype = {
initialize: function() {
CIPNet.Extenders.LookupBehavior.callBaseMethod(this, 'initialize');
},
dispose: function() {
CIPNet.Extenders.LookupBehavior.callBaseMethod(this, 'dispose');
},
//
// Property accessors
//
get_LookupArray: function() {
return this._lookupArray;
},
set_LookupArray: function(value) {
this._lookupArray = value;
},
get_TargetTextBoxID: function() {
return this._targetTextBoxID;
},
set_TargetTextBoxID: function(value) {
this._targetTextBoxID = value;
var that = this;
$(function() {
var showSuggestion = function () {
$(this).autocomplete("search", "");
};
var availableTags = that._lookupArray;
$("#" + value).autocomplete({
source: availableTags,
delay: 0,
minLength: 0
}).click(showSuggestion);
});
}
};

Resources