Extend events of Infragistics WebDropDown - asp.net

I'm intending to attach my custom handler to the "DropDownClosing" event of WebDropDown.
I tried the below for a sample.
$IG.WebDropDown.prototype = {
openDropDown: function () { alert(1); }
}
But it throws error while being parsed by DOM (Uncaught ReferenceError: $IG is not defined).
Interestingly, the below one works but it shows the alert and skips all other native functionality. (e.g After alert the dropdown is not opening)
$IG.WebDropDown.prototype.openDropDown = function () { alert(1); }
The goal is, all the webdropdowns in my application should use my customer function and I want to configure this at one place rather than adding the "DropDownClosing" client event for every webdropdown.
What is the right approach to extend an event of a control in infragistics.

You can use the same client event handler for all WebDropDowns on the page, but you still have to tell each to subscribe to this handler and to use it:
<ig:WebDropDown ID="myDropDown1" runat="server">
<ClientEvents DropDownClosing="dropDownClosing" />
</ig:WebDropDown>
<ig:WebDropDown ID="myDropDown2" runat="server">
<ClientEvents DropDownClosing="dropDownClosing" />
</ig:WebDropDown>
<script type="text/javascript">
function dropDownClosing(sender, eventArgs) {
alert(1);
}
</script>
What you've tried is an override of the WebDropDown openDropDown client method. This will override the opening functionality for the control, and thus the drop down wouldn't open, unless you re-implement the functionality yourself, or use a cached reference to the original implementation. This is not the same as attaching an event handler.

Related

Button, changing CommandName and CommandArgs on the client side

Is there a way to change the values for these two attributes on the client side and have it reflected on the server side after the postback. I tried it but it does not seem to work. I wanted to have one button on the page that I would delegate submits too, and assign these two arguments on the client side. Seems like not possible. Any idea?
Assuming there is a button named "cmd" in the form
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#<%=cmd.ClientID %>").click(function () {
$(this).attr("CommandName", "do").attr("CommandArgument", "arg2");
});
});
</script>
If one checks the value after postback they are still the same as they were before postback.
I tried you're code and it works fine.
Just make sure you're button is not generating a postback by adding OnClientClick="return false;":
<asp:Button ID="cmd" runat="server" Text="Button" OnClientClick="return false;"></asp:Button>
Also you won't see the difference in "view source" on your browser. But the change has been made in the DOM. Use firebug and add the console.log to see for yourself:
$("#<%=cmd.ClientID %>").click(function () {
$(this).attr("CommandName", "do").attr("CommandArgument", "arg2");
console.log(this);
});
The console.log(this) gave me the following:
EDIT:
If you think about it. If the button creates a postback, then the button will reset itself to normal once the page loads again.
EDIT #2:
I don't need the change on the client
side, I need it on the server side.
That was the whole point of the
question. I need to see the change on
the server side, and it does not seem
to be possible. – epitka
Okay... Well, in that case. It is not possible. "CommandArgument" and "CommandName" means nothing to the client and is not accessible.
However there are work arounds. But depending on the context of your application they might not be useful to you.
You could try using your own attributes like the answer suggested here.
Or you could execute the __doPostBack on the client side and pick up the __EVENTARGUMENT on the code behind.
(The link button is there to generate the __doPostBack function by asp.net.)
Like such:
<script type="text/javascript" language="javascript">
function DoPostBack() {
__doPostBack('cmd', 'thesearemyarguments');
}
</script>
Page:
<asp:Button ID="cmd" runat="server" Text="Button"
OnClientClick="DoPostBack(); return true;"
onclick="cmd_Click" ></asp:Button>
<asp:LinkButton ID="LinkButton1" runat="server" Visible="false">LinkButton</asp:LinkButton>
Code Behind:
protected void cmd_Click(object sender, EventArgs e)
{
Response.Write(Request.Params["__EVENTARGUMENT"]);
}
I was having the same problem here, I found the solution was to use an ajax call to send my buttons id to a function where i can set it as a session variable. Because the asp control I wanted to update could not be accessed from within a static call. On success of the ajax call I click a hidden button which uses a non static click event to manipulate the session variable i set and update the control
My links were generated within a repeater, and they correspond to different rooms of a house. When you click on the link there is another repeater that has to update to show products that are sold which are relevant to the room of the house that was clicked on
my link that is generated from the repeater
<%#Eval("DocumentName") %>
my client side method
$('.changeroom').each(function () {
$(this).on('click', function () {
var id = $(this).attr('data-id');
var object = { 'sender': id };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/App/Page Templates/FindByRoom.aspx/UpdateRoomID",
data: JSON.stringify(object),
success: function() {
$('#btnID').click();
}
});
});
});
btnID is a simple aspButton with a server side click event
and finally my server side methods
protected void btnChangeRoom_OnClick(object sender, CommandEventArgs e)
{
int id = 0;
if (Session["RoomID"] == null) return;
Int32.TryParse(Session["RoomID"].ToString(), out id);
if (id == 0) return;
//do something with your buttons id
//i updated the path of a repeater and reloaded the data
}
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void UpdateRoomID(string sender)
{
HttpContext.Current.Session["RoomID"] = sender;
}

JQuery / ASP.NET newbie questions about <asp:Button>

Hey all, having an issue getting asp buttons to interact with JQuery. I'm basically trying to hide a div that contains a form and replace it with an processing image. It works fine for me when I use an HTML input button as the trigger but when I use an aspButton nothing happens.
This works (the id of the HTML button is 'btnSubmit'):
<script>
$('#btnSubmit').click(function () {
$('#form1').fadeOut('fast', function () {
$('#processing').fadeIn('fast', function () {
});
});
});
</script>
This doesn't (the id of the ASP button is 'btnSubmitASP'):
<script>
$('#btnSubmitASP').click(function () {
$('#form1').fadeOut('fast', function () {
$('#processing').fadeIn('fast', function () {
});
});
});
</script>
Any idea what the trick is to get the asp button to do this?
Thanks
The ASP.net server ID for the control is different from the html ID. (ASP.net calls this the client ID). You can get the client id this way:
$('#<%= this.btnSubmitASP.ClientID %>').click( /* etc */ );
If you are using asp.net 4.0 you can set the button's ClientIDMode property ='Static'. This will stop the runtime from mucking with the ID.
Try this:
<script>
$('<%=btnSubmitASP.ClientID%>').click(function () {
$('#form1').fadeOut('fast', function () {
$('#processing').fadeIn('fast', function () {
});
});
});
</script>
Explanation:
ASP.NET renames all of its controls when they get sent to the client. Consequently, your ASP.NET Button does not have a client ID of "btnSubmitASP" client-side. The above code calls the server control on the server side and gets its client-id to use in the jQuery code.
Alternatively, you can use jQuery selectors:
<script>
$("[id$='_btnSubmitASP']").click(function () {
$('#form1').fadeOut('fast', function () {
$('#processing').fadeIn('fast', function () {
});
});
});
</script>
This will look for controls whose client ID ends with "_btnSubmitASP".
Another alternative to using the ClientId is to assign a unique class to the ASP:button. Your selector would then look like this:
<asp:button runat="server" CssClass="submitbutton">/<asp:button>
<script>
$("submitbutton").click(function () {
$('#form1').fadeOut('fast', function () {
$('#processing').fadeIn('fast', function () {
});
});
});
</script>
For ASP.NET buttons you should use the OnClientClick property as it has built in client side scripting added to the button to do its post back behavior. Example:
<asp:Button ID="btnSubmitASP" runat="server"
OnClientClick="yourJqueryFunction();" />
If you return false in the OnClientClick you will prevent the default behavior of the button preventing a PostBack. Doing nothing or returning true will cause the PostBack to occur. By using this method you don't need to know the name of your Button to attach the script code.
To just get your code working though, you need to get the ClientID of the control inline to creating you script so change the following line to use the ClientID property of the Button:
$('#<%= btnSubmitASP.ClientID %>').click(function () {
You need to get the ClientID because ASP.NET adds to name to namespace it and prevent duplication of names. If you look at the ASP.NET Button, the you will notice the name and ID properties have a lot more added to it like:
<input type="submit" name="ctl00$ContentPlaceHolder1$btnSubmitASP" value="Test"
id="ctl00_ContentPlaceHolder1_btnSubmitASP" />
My knowledge of jQuery is very shallow, but I can give you one tip: Remember that jQuery is being executed client-side, while the ASP button is rendered on the server and returned in the response.
Double-check the HTML markup for the button when your page is returned from the server, and make sure it's structured as you expect. Perhaps the ID attribute isn't being set as expected, for example.
Your button controller is runat="server" so this means that .NET will modify the controller's id before rendering it in HTML.
jQuery tries to use that ID to do whatever you want to do with it. But the ID is no longer the same.
Use a class instead on your button. I know it's not as fast as an ID, but it's the best way to do it because .NET will not modify your css class.
If your ASP:Button contains runat="server" then .NET will modify the ID value before it get to the DOM, so your resulting <input> will probably wind up looking like
<input id="ctl00_ContentPlaceHolder1_btnSubmitASP" />
Therefore, your jQuery selector $('#btnSubmitASP') is no longer valid because the ID has changed.
Use Firebug or Right click -> View source to confirm the actual ID value.

Adding a ServiceReference programmatically during async postback

Is it possible to add a new ServiceReference instance to the ScriptManager on the Page during an asynchronous postback so that subsequently I can use the referenced web service through client side script?
I'm trying to do this inside a UserControl that sits inside a Repeater, that's why adding the ScriptReference programmatically during Page_Load does not work here.
EDIT 2: This is the code I call from my UserControl which does not do what I expect (adding the ServiceReference to the ScriptManager during the async postback):
private void RegisterWebservice(Type webserviceType)
{
var scm = ScriptManager.GetCurrent(Page);
if (scm == null)
throw new InvalidOperationException("ScriptManager needed on the Page!");
scm.Services.Add(new ServiceReference("~/" + webserviceType.Name + ".asmx"));
}
My goal is for my my UserControl to be as unobtrusive to the surrounding application as possible; otherwise I would have to statically define the ServiceReference in a ScriptManagerProxy on the containing Page, which is not what I want.
EDIT:
I must have been tired when I wrote this post... because I meant to write ServiceReference not ScriptReference. Updated the text above accordingly.
Now I have:
<asp:ScriptManagerProxy runat="server" ID="scmProxy">
<Services>
<asp:ServiceReference Path="~/UsefulnessWebService.asmx" />
</Services>
</asp:ScriptManagerProxy>
but I want to register the webservice in the CodeBehind.
Try something like this...
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "script1", "~/js/myjs.js");
}
Edit:
After checking your issue, Here is the reason why it is not working:
When you add ServiceReference to ScriptManager > Services section manually in page. It adds 1 client script include directive.
e.g:
<script src="TestService.asmx/jsdebug" type="text/javascript"></script>
or
<script src="TestService.asmx/js" type="text/javascript"></script>
which provide you to accessibility to your Frontend.Web.YourScriptMethods,
Now when you add ServiceReference in async postback - It is not adding this client script inclue. So you get client script error - method is undefined.
But i figured out a workaround for this; (do not know it is right way to do it)
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "testservice", "TestService.asmx/js");
}
You can replace the "TestService.asmx" path according to your project/web service.
This way you can achieve what you want.
Hope this helps,
Krunal Mevada
Old Ans:
Use following:
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
ScriptManager.GetCurrent(this).Services.Add(new ServiceReference("~/Service.asmx"));
}

How to call a client-side method from an asp.net method?

I have the following javascript:
<script type="text/javascript">
function showjQueryDialog() {
$("#dialog").dialog("open");
}
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons: { "Renew Membership": function() { $(this).dialog("close"); } }
});
});
</script>
I have an asp:Button on the page which logs the user it. This is the sample of what I want to occur when the button is clicked on the server-side:
protected void LoginButton_OnClick(object sender, EventArgs e)
{
UserProfile profile = UserProfile.GetUserProfile(txtUserName.Text);
TimeSpan ts = profile.Expiration.Subtract(DateTime.Now);
if(ts.Days <= 30)
//call showJQueryDialog() to open the dialog box
Page.ClientScript.RegisterStartupScript(typeof(Login2), "showjquery",
"showJQueryDialog();", true);
else
//log the user in as normal.
}
Also is how would I attach a method such as the following to the Renew Button on the Dialog
public void Renew()
{
Response.Redirect("Renew.aspx");
}
As calling client side function is not possible I would suggest to emit in javascript the information required for the decision and make everything happen on the client side.
Alternatively you can do need a page reload, as suggested from previous commenter.
if(ts.Days <= 30)
ScriptManager.RegisterStartupScript(
typeof(MyPage), "showjquery",
"$(document).ready(function() { showJQueryDialog(); };",
true
)
else
//log the user in as normal.
Put that right where you have: //call showJQueryDialog() to open the dialog box
Update 1: You seem to be using an update panel, in that case you need to use ScriptManager.RegisterStartupScript
Update 2: You also want to wrap the js call in a jquery .ready call, so it isn't triggered before the dialog has been configured. This is better than hooking up the body onload because onload waits for images to be loaded so .ready will show sooner (depending on the images and other bits of info loaded).
I really don't understand Freddy's approach to this at all. I am misunderstanding something maybe. The way I see it, there are only two possibilities here, as devdimi point out. Either:
a) Do all the logic in the client-side onClick javascript. You could call an AJAX method that performs the action in the server-side OnClick, then call your jQuery popup in the AJAX callback.
b) Do a postback, handle the server-side OnClick, then attach javascript for the page that runs in the body onLoad event:
body.Attributes.Add("onLoad", "showJQueryDialog();")
I would keep a hidden LinkButton and then call the __doPostBack method in javascript.
<asp:LinkButton runat="server" ID="Renew" OnClick="Renew_Click" style="display:none" />
jQuery
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons: { "Renew Membership": function() {
$(this).dialog("close");
__doPostBack('Renew', '');
// or if inside a master page something like this
__doPostBack('ctl00$ContentPlaceHolder1$Renew', '');
} }
});
});
I have a somewhat similar issue with IE8.
We're using ASP.NET and anytime we do a Response.Redirect within the PageLoad/Control-Events IE8 sets all the base DOM objects to undefined (Image, window, document)
But if we do the redirect during the PreInit event then IE8 is fine.. Lovely

LinkButton does not invoke on click()

Why doesn't this work?
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.myButton').click();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton id="ttt" runat="server" PostBackUrl="~/Default.aspx" CssClass="myButton">Click</asp:LinkButton>
</div>
</form>
Do you want to submit the form, or add a Click event?
Your link button translates to
<a id="ttt" class="myButton" href="javascript:WebForm_DoPos[...]">Click</a>
, so it has no on-click javascript. Therefore, .click(); does nothing.
I haven't test it, but maybe this will work:
eval($('.myButton').attr('href'));
trigger('click') fires jQuery's click event listener which .NET isn't hooked up to. You can just fire the javascript click event which will go to (or run in this case) what is in the href attribute:
$('.myButton')[0].click();
or
($('.myButton').length ? $('.myButton') : $('<a/>'))[0].click();
If your not sure that the button is going to be present on the page.
Joe
If you need the linkbutton's OnClick server-side event to fire, you need to use __doPostback(eventTarget, eventArgument).
ex:
<asp:LinkButton ID="btnMyButton" runat="Server" OnClick="Button_Click" />
<script type="text/javascript">
function onMyClientClick(){
//do some client side stuff
//'click' the link button, form will post, Button_Click will fire on back-end
//that's two underscores
__doPostBack('<%=btnMyButton.UniqueID%>', ''); //the second parameter is required and superfluous, just use blank
}
</script>
you need to assign an event handler to fire for when the click event is raised
$(document).ready(function() {
$('.myButton', '#form1')
.click(function() {
/*
Your code to run when Click event is raised.
In this case, something like window.location = "http://..."
This can be an anonymous or named function
*/
return false; // This is required as you have set a PostbackUrl
// on the LinkButton which will post the form
// to the specified URL
});
});
I have tested the above with ASP.NET 3.5 and it works as expected.
There is also the OnClientClick attribute on the Linkbutton, which specifies client side script to run when the click event is raised.
Can I ask what you are trying to achieve?
The click event handler has to actually perform an action. Try this:
$(function () {
$('.myButton').click(function () { alert('Hello!'); });
});
you need to give the linkButton a CssClass="myButton" then use this in the top
$(document).ready(function() {
$('.myButton').click(function(){
alert("hello thar");
});
});
That's a tough one. As I understand it, you want to mimic the behavior of clicking the button in javascript code. The problem is that ASP.NET adds some fancy javascript code to the onclick handler.
When manually firing an event in jQuery, only the event code added by jQuery will be executed, not the javascript in the onclick attribute or the href attribute. So the idea is to create a new event handler that will execute the original javascript defined in attributes.
What I'm going to propose hasn't been tested, but I'll give it a shot:
$(document).ready(function() {
// redefine the event
$(".myButton").click(function() {
var href = $(this).attr("href");
if (href.substr(0,10) == "javascript:") {
new Function(href.substr(10)).call(this);
// this will make sure that "this" is
// correctly set when evaluating the javascript
// code
} else {
window.location = href;
}
return false;
});
// this will fire the click:
$(".myButton").click();
});
Just to clarify, only FireFox suffers from this issue. See http://www.devtoolshed.com/content/fix-firefox-click-event-issue. In FireFox, anchor (a) tags have no click() function to allow JavaScript code to directly simulate click events on them. They do allow you to map the click event of the anchor tag, just not to simulate it with the click() function.
Fortunately, ASP.NET puts the JavaScript postback code into the href attribute, where you can get it and run eval on it. (Or just call window.location.href = document.GetElementById('LinkButton1').href;).
Alternatively, you could just call __doPostBack('LinkButton1'); note that 'LinkButton1' should be replaced by the ClientID/UniqueID of the LinkButton to handle naming containers, e.g. UserControls, MasterPages, etc.
Jordan Rieger

Resources