ajaxcontroltoolkit CascadingDropDown call method when control populated - javascript

I have a CascadingDropDown control in my page. I want to do some jquery actions when the dropdown is populated. according to the documentation , there is a event called (populated) for that purpose.
I added that code in my page:
function raise_populated() {
alert()
}
and here is how i use the dropdown
<asp:DropDownList ID="listcat" runat="server" required></asp:DropDownList>
<ajaxToolkit:CascadingDropDown ID="cdlisteCategorie" TargetControlID="listcat" PromptText='Catégories'
ServicePath="../Webservice/CategorieService.asmx" ServiceMethod="GetCategories" Category="IDCATS" runat="server" LoadingText="Chargement..."></ajaxToolkit:CascadingDropDown>
the raise_populated never fires.

I've found the solution here
function pageLoad(sender, args)
{
var cdd = $find("behaviorIDofCDD");
cdd.add_populated(onPopulated);
}
function onPopulated()
{
//any function to be called
}

Related

Javascript Modal Box OnCommand not working

<div>
<asp:Repeater ID="ProductView" runat="server" OnItemDataBound="Repeater1_ItemDataBound" >
<ItemTemplate>
<asp:Label ID="lblAddressID" runat="server" Text='<%# Eval("OrderNumer") %>' Visible = "false" />
<asp:LinkButton ID="Delete" CssClass="MordersButton" OnCommand="btnDelete_Click" OnClientClick="return ShowMessage();" runat="server" Text='<%#Eval("Delete") %>'></asp:LinkButton></h5>
</ItemTemplate>
</asp:Repeater>
</div>
<script type="text/javascript">
function ConfirmBox(msgtitle, message, controlToFocus) {
$("#msgDialogAlert").dialog({
autoOpen: false,
modal: true,
title: msgtitle,
closeOnEscape: true,
buttons: [{
text: "Yes",
click: function () {
$(this).dialog("close");
if (controlToFocus != null)
controlToFocus.focus();
}
},
{
text: "No",
click: function () {
$(this).dialog("close");
if (controlToFocus != null)
controlToFocus.focus();
}
}],
close: function () {
$("#operationMsgAlert").html("");
if (controlToFocus != null)
controlToFocus.focus();
},
show: { effect: "clip", duration: 200 }
});
$("#operationMsgAlert").html(message);
$("#msgDialogAlert").dialog("open");
};
function ShowMessage() {
ConfirmBox("This is Title - Please Confirm", "Are you sure you wanted to delete? This cannot be undone!", null);
return false;
}
</script>
protected void btnDelete_Click(object sender, EventArgs e)
{
RepeaterItem item = (sender as LinkButton).Parent as RepeaterItem;
string name = (item.FindControl("Delete") as LinkButton).Text.Trim();
string OrderNumber = (item.FindControl("lblAddressID") as Label).Text.Trim();
{
using (SqlCommand cmd = new SqlCommand("DC_ManageOrders_Update"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CategoryType", name);
cmd.Parameters.AddWithValue("#OrderNumber", OrderNumber);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
this.FlavorImage1Bind();
}
If I Click the button Yes after the modal box opened the delete is not happening. Please help how can i achieve this
i want to run the btnDelete_Click code to delete the record, without modal box through normal javascript i can able to delete the record.
If someone able to help me it will be very usefull to me ...
Ok, the problem here?
When you use onClientClick, you "goal" is to return true (server side code runs), or false - server side button event does not run.
So, you can say use a js confirm box. That's because confirm() HALTS the code.
However, jquery.UI, and in FACT MOST web based software does NOT halt code. Most web based controls (bootstrap dialogs, and jQuery.UI) are NOT modal. They are asynchronous in operation. Blocking, or halting code in js is simple RARE allowed these days.
So, most suggested solutions center around say disabling the event code for the button, and then you execute a _doPostBack(). This is not bad, but then you can't have that button conditional run based on return of true/false. So you wind up with a extra button, extra _doPoast back. So most solutions are really quite poor.
So, when this code runs:
OnClientClick="return ShowMessage();
The above code runs async - does NOT wait. So the dialog pops, but the code continues running and the server side button click will fire!! - (and the dialog that was displayed will of course colipase since we have a page post back.
So, we want:
avoid document ready solutions - they are horrid to debug
document ready means we have a VERY difficult time following code flow.
we want a simple function - has to return true/false.
but, jQuery.UI dialogs do not wait, and they don't halt code.
So, to avoid world poverty, 2-3 extra routines, messy _doPostback, and code to disable the button?
Do it this way:
Adopt a code standard that you create a true/false var of the SAME name of the function (with "OK" on the end), and scope the variable to that function.
Also, I assume that the delete button when clicked (without the onclientclick) works as you wish.
<script>
var mypopok = false; // runs on browser load
function mypop() {
if (mypopok) {
return true;
}
mydiv = $('#dlg1');
mydiv.dialog({
autoOpen: false, modal: true, title: 'Yes/no test', width: '250px',
position: { my: 'top', at: 'top+150' },
buttons: {
'ok': function () {
mypopok = true;
mydiv.dialog('close');
$('#Button1').click();
},
'cancel': function () {
mydiv.dialog('close')
}
}
});
// Open the dialog
// if dialog has MORE then just ok, cancel, and say has text
// box, check box in content, then you MUST move back to form
mydiv.parent().appendTo($("form:first"))
mydiv.dialog('open')
return false;
}
</script>
Now, the button click code looks like this:
<asp:Button ID="Button1" runat="server" Height="48px" Text="Button" Width="171px"
ClientIDMode="Static" OnClientClick="return mypop();"/>
So what will occur?
You will click on the button - the code will run and return false!!! - (remember, it does NOT wait or halt). Now the dialog does pops, but button event code will not trigger.
Based on yes or no, we set that bol flag to true or false. If cancel, then we just close the dialog. If "ok", then we set the flag = true and RE-CLICK the SAME button. Now the button click runs again, but we in our routine return true before the pop dialog code runs, and thus now the server side event click runs.
We:
did not have to consider using await (promise)
did not have to add a extra button
did not have document ready and code ALL OVER in the page
did not have to add extra buttons and events.
code is liner - easy to read - all in one spot.
Now I would consider adding the parameters to the Actual OnClientClick,
Say like this:
OnClientClick="return mypop('This is Title - Please Confirm',
'Are you sure you wanted to delete? This cannot be undone!', null);"
And add the parms to the mypop.
You can't really use two routines like you have, since as noted this:
function ShowMessage() {
ConfirmBox("This is Title - Please Confirm", "Are you sure you wanted to delete? This cannot be undone!", null);
return false;
}
Confirmbox does NOT halt or wait - the code will "run right though" and immediate return false.
So use the flag trick I outline, and re-click the SAME button again when user hits ok. That way, you don't wire up 3-4 routines, and you don't need to add extra buttons or use _DoPostBack() in the js code.

Call a codebehind function from a javascript method

I am trying to call a codebehind function with javascript. I need to make some operations with my gridview.
Here is my javascript:
function hideColumn() {
var gridrows = $("#GridViewHdcvi tbody tr");
AddTeklif.RemoveTextBoxes();
for (var i = 0; i < gridrows.length; i++) {
gridrows[i].cells[5].style.display = "none";
}
return false;
};
And my codebehind:
[WebMethod]
public static void RemoveTextBoxes()
{
foreach (GridViewRow row in GridViewHdcvi.Rows)
{
TextBox txb = (TextBox)row.FindControl("txtAdet");
string adet = txb.Text;
txb.Visible = false;
Label lbl = (Label)row.FindControl("LblAdet");
lbl.Text = adet+" $";
}
}
I have an error like 'An object reference is required for the non-static field,method, or property CRM.AddTeklif.GridViewHdcvi' in 'GridViewHdcvi.Rows'. When I make method's name 'public void RemoveTextBoxes()' error gone but method doesn't working since it is not static.
It seems that you are mixing two different concepts. JavaScript is run from the browser and will not have any access to your server code. What you are doing here is attempting to call a WebMethod when your page is Rendered to be sent to the browser.
A better approach would be to convert your RemoveTextBoxes method to jQuery as what you are wanting to do is modify the DOM.
This is how you would call your JavaScript function hideColumn() from a code behind.
Put this in the method where you want to call your javascript function.
Page.ClientScript.RegisterStartupScript(this.GetType(), "hideColumn", "hideColumn(;", true);
To call a codebehind from a javascript function you have to play some tricks.
1.) create a hidden button control. You have to hide it within the CssClass
<asp:Button ID="hdnButton" runat="server" CssClass="hidden" />
.hidden {
display: none;
}
2.) Create a click hdnButton method in your code behind
3.) Call the hidden button click event from your javascript
function CallCodeBehind() {
document.getElementById('<%= hdnButton.ClientID%>').click();
}

Knockout/JavaScript Ignore Multiclick

I'm having some problems with users clicking buttons multiple times and I want to suppress/ignore clicks while the first Ajax request does its thing. For example if a user wants add items to their shopping cart, they click the add button. If they click the add button multiple times, it throws a PK violation because its trying to insert duplicate items into a cart.
So there are some possible solutions mentioned here: Prevent a double click on a button with knockout.js
and here: How to prevent a double-click using jQuery?
However, I'm wondering if the approach below is another possible solution. Currently I use a transparent "Saving" div that covers the entire screen to try to prevent click throughs, but still some people manage to get a double click in. I'm assuming because they can click faster than the div can render. To combat this, I'm trying to put a lock on the Ajax call using a global variable.
The Button
<span style="SomeStyles">Add</span>
Knockout executes this script on button click
vmProductsIndex.AddItemToCart = function (item) {
if (!app.ajaxService.inCriticalSection()) {
app.ajaxService.criticalSection(true);
app.ajaxService.ajaxPostJson("#Url.Action("AddItemToCart", "Products")",
ko.mapping.toJSON(item),
function (result) {
ko.mapping.fromJS(result, vmProductsIndex.CartSummary);
item.InCart(true);
item.QuantityOriginal(item.Quantity());
},
function (result) {
$("#error-modal").modal();
},
vmProductsIndex.ModalErrors);
app.ajaxService.criticalSection(false);
}
}
That calls this script
(function (app) {
"use strict";
var criticalSectionInd = false;
app.ajaxService = (function () {
var ajaxPostJson = function (method, jsonIn, callback, errorCallback, errorArray) {
//Add the item to the cart
}
};
var inCriticalSection = function () {
if (criticalSectionInd)
return true;
else
return false;
};
var criticalSection = function (flag) {
criticalSectionInd = flag;
};
// returns the app.ajaxService object with these functions defined
return {
ajaxPostJson: ajaxPostJson,
ajaxGetJson: ajaxGetJson,
setAntiForgeryTokenData: setAntiForgeryTokenData,
inCriticalSection: inCriticalSection,
criticalSection: criticalSection
};
})();
}(app));
The problem is still I can spam click the button and get the primary key violation. I don't know if this approach is just flawed and Knockout isn't quick enough to update the button's visible binding before the first Ajax call finishes or if every time they click the button a new instance of the criticalSectionInd is created and not truely acting as a global variable.
If I'm going about it wrong I'll use the approaches mentioned in the other posts, its just this approach seems simpler to implement without having to refactor all of my buttons to use the jQuery One() feature.
You should set app.ajaxService.criticalSection(false); in the callback methods.
right now you are executing this line of code at the end of your if clause and not inside of the success or error callback, so it gets executed before your ajax call is finished.
vmProductsIndex.AddItemToCart = function (item) {
if (!app.ajaxService.inCriticalSection()) {
app.ajaxService.criticalSection(true);
app.ajaxService.ajaxPostJson("#Url.Action("AddItemToCart", "Products")",
ko.mapping.toJSON(item),
function (result) {
ko.mapping.fromJS(result, vmProductsIndex.CartSummary);
item.InCart(true);
item.QuantityOriginal(item.Quantity());
app.ajaxService.criticalSection(false);
},
function (result) {
$("#error-modal").modal();
app.ajaxService.criticalSection(false);
},
vmProductsIndex.ModalErrors);
}
}
you could use the "disable" binding from knockout to prevent the click binding of the anchor tag to be fired.
here is a little snippet for that. just set a flag to true when your action starts and set it to false again when execution is finished. in the meantime, the disable binding prevents the user from executing the click function.
function viewModel(){
var self = this;
self.disableAnchor = ko.observable(false);
self.randomList = ko.observableArray();
self.loading = ko.observable(false);
self.doWork = function(){
if(self.loading()) return;
self.loading(true);
setTimeout(function(){
self.randomList.push("Item " + (self.randomList().length + 1));
self.loading(false);
}, 1000);
}
}
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
Click me
<br />
<div data-bind="visible: loading">...Loading...</div>
<br />
<div data-bind="foreach: randomList">
<div data-bind="text: $data"></div>
</div>

Backbone.js event always activated [duplicate]

i have the following code which extends the JQuery and adds a method to the JQuery:
$.fn.attachWithMessage = function () {
$(this).focusin(showMessage());
}
function showMessage() {
alert('hi');
}
so I can use that code as follows :
<input type="text" name="name" id="textbox" />
$(document).ready(function () {
$("#textbox").attachWithMessage ();
});
when I load the page for the first time, a message box shows up with ('hi') message.
even if I didn't click in the text box.
I also tried the click event, and the message still shows automatically.
any ideas ??
The issue here is that when you pass showMessage() as a parameter to focusin, the function showMessage is executed and the return value is passed to focusin.
Instead you need to pass a reference to the function (without the paranthesis).
Use the following code to extend:
$.fn.attachWithMessage = function () {
$(this).focusin(showMessage);
}
Working example# http://jsfiddle.net/eXEP5/
EDIT:
If you want to pass a parameter to showMessage then try this:
$.fn.attachWithMessage = function () {
var param1 = "Some Param";
$(this).focusin(function(){
showMessage(param1); //Make sure showMessage is modified accordingly for the parameters.
});
}
just remove the parenthesis
$(this).focusin(showMessage());
should be
$(this).focusin(showMessage);
Hope this helps

Javascript pageLoad not executing in a master page

What causes the following pageLoad to not execute in a master page? The first alert executes as expected, but the pageLoad function is not being invoked. How can I use the function within a master/content page?
<script type="text/javascript">
alert('test');
function pageLoad(sender, args) {
alert('pageLoad');
}
</script>
I'm assuming a script manager control is present in your master page? I'm not sure if the client-side pageLoad method is only called on the initial page load. I do know that if you're looking for ajax postback page load hooks, try the client-side PageRequestManager.
MAke sure that the code below is place inside the script manager.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<script type="text/javascript" >
(function() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm)
{
prm.add_endRequest(
function (sender, args) {
// do your stuff
// Handle a weird occurence where an error is returned but the error code is 0, i.e. no error.
if(args.get_error() && args.get_error().name === 'Sys.WebForms.PageRequestManagerServerErrorException')
{
args.set_errorHandled(args._error.httpStatusCode == 0);
}
});
}
})();
</script>
<%-- Other markup --%>
</asp:ScriptManager>
Window Load Event
window.onload = function() {
alert('pageLoad');
}
Self Executing Function
(function() {
alert('pageLoad');
})();

Categories

Resources