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

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);
});
}
};

Related

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">

How to Call Pagemethod in Angular js Service

i am new in Angular js.
Static Method in Code Behind
[WebMethod]
public static string GetPracticeLocations()
{
return "[{ id: 1, name: Test AccountName}]";
}
Angular JS Service
appSettings.service('PracticeLocationsService', function () {
this.getPracticeLocations = function () {
var PracticeLocationsData = PageMethods.GetPracticeLocations();
return PracticeLocationsData;
};
});
i want to know how to implement page method in Angular JS.
Any helpful suggustein apricited
Thanks
Probably I'm too late, but you could use defer to call a page method and return a promise,
var getPracticeLocations = function () {
var deferred = $q.defer();
PageMethods.GetPracticeLocations(function (response) {
if (response) {
deferred.resolve({ result: angular.fromJson(response) });
} else {
deferred.resolve({ result: null });
}
},
function (msg, code) {
deferred.reject(msg);
});
return deferred.promise;
};
You want to look at factory() and $http
pseudo code:
angular.factory("PageMethods", ["$http", function($http){
return {
GetPracticeLocations : function(){
return $http.get("/someurl");
}
}
}]);

this.get_element() of asp.net ajax is not working in functions I declare

I try to access the element in my own function through this.get_element() but it does not work.
Type.registerNamespace("LabelTimeExtender1");
LabelTimeExtender1.ClientBehavior1 = function(element) {
LabelTimeExtender1.ClientBehavior1.initializeBase(this, [element]);
var testelement=this.get_element();
var timestamp= this.get_element().attributes['TimeStamp'].value;
alert("in constructor");
},
LabelTimeExtender1.ClientBehavior1.prototype = {
initialize: function() {
LabelTimeExtender1.ClientBehavior1.callBaseMethod(this, 'initialize');
setInterval (this.timer,1000);
alert("after");
},
dispose: function() {
//Add custom dispose actions here
LabelTimeExtender1.ClientBehavior1.callBaseMethod(this, 'dispose');
},
timer: function(){
debugger;
var date= new Date(this.timestamp);
var datenow= new Date ();
this._element.innerText=" ";
if(date.getUTCFullYear<datenow.getUTCFullYear)
{
var myelement= this.get_element();
myelement .innerHTML= date.getUTCFullYear.toString();
}
if(date.getUTCMonth<datenow.getUTCMonth)
{
this.get_element().innerHTML=date.getUTCMonth.toString();
}
if(date.getUTCDay<datenow.getUTCDay)
{
this.get_element().innerHTML=date.getUTCDay.toString();
}
if(date.getUTCHours <datenow.getUTCHours )
{
this.get_element().innerHTML=date.getUTCHours .toString();
}
if(date.getUTCMinutes<datenow.getUTCMinutes)
{
this.get_element().innerHTML=date.getUTCMinutes.toString();
}
}
}
LabelTimeExtender1.ClientBehavior1.registerClass('LabelTimeExtender1.ClientBehavior1', Sys.UI.Behavior);
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
Here I am trying to access the custom attribute 'TimeStamp' and calcutate the time and assign to the label to show.
Try to invoke your function through delegates.Then you will not have problem with [this] keyword
something like this:
setInterval (Function.createDelegate(this, this.timer),1000)

MVC3 JSON Return to Edit Page

So I have some javascript code that sends data to my controller:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#newGrade").click(function () {
var newGradeName = $("#newGradeName").val();
var newGradeValue = $("#newGradeValue").val();
var vSchoolID = $("#SchoolID").val();
if (newGradeName != null && newGradeValue != null) {
$.ajax({
url: '#Url.Action("NewGrade", "School")',
data: { gradeName: newGradeName, gradeValue: newGradeValue, schoolID: vSchoolID },
type: 'POST',
traditional: true,
success: function (data) {
if (data.status)
window.location = data.route;
},
error: function () {
return false;
}
});
}
});
});
</script>
Controller:
public ActionResult NewGrade(String gradeName, Int32 gradeValue, Guid schoolID)
{
School school = schoolRepository.GetByID(schoolID);
school.Grades.Add(
new Grade
{
GradeID = Guid.NewGuid(),
Name = gradeName,
NumericalValue = gradeValue
});
schoolRepository.Update(school);
schoolRepository.Save();
if (Request.IsAjaxRequest())
{
var json = new { status = true, route = Url.RouteUrl(new { action = "Edit", id = schoolID }) };
return Json(json, JsonRequestBehavior.AllowGet);
}
return View();
}
My issue now is I want to return to my Edit page (possibly refreshing the page, but not the data, or just refresh the entire page), but my Edit page takes an ID (schoolID). Shown here when pressing the button to get to the Edit page:
<i class="icon-pencil"></i> Edit
Try window.location.href and see what happens.
success: function(data) {
if (data.status)
window.location.href = data.route;
},
This should work fine assuming you are getting a JSON reponse from your action method like
{"status":"true","route":"/School/Edit/1"}
where 1 is the ID of new record.

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

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.

Resources