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

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

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

Hide and Show div's on Button Click in a UpdatePanel

I am using UpdatePanel ---> LinkButton --> Div --->Table Structure.
When I click the Linkbutton the div has to show the table format first and has to execute the code in its OnClick event, the problem I am facing is I've tried so many jquery functions shown below:
<asp:LinkButton ID="lnkbtnUnitAdd" runat="server" OnClientClick="Toggledivs()" OnClick="lnkbtnAdd_Click" Text="Add" ></asp:LinkButton>
Even if I used:
$(document).ready(function()
{
$("#lnkbtnUnitAdd").click(function () {
$("#divUnit").show("slow"); return false;
});
});
or
function Toggledivs()
{
$("#lnkbtnUnitAdd").click(function () {
$("#divUnit").show("slow"); return false;
});
}
or without using the OnClientClick property in LinkButton
the result is same, as the function is returning false in button Onclient click or document.ready function(), therefore buttons Onclick event is not firing.
And if I comment the return false, the div is not showing up properly.
Please help how to deal as the whole process is running in an updatepanel.
You might have to use Control.ClientID in this case. Try this
$(document).ready(function(){
$("#<%=lnkbtnUnitAdd.ClientID%>").click(function () {
$("#divUnit").show("slow"); return false;
});
});
I won't recommend adding the event handler in HTML. But the following code should work. You don't have to assign the click event again.
function Toggledivs()
{
$("#divUnit").show("slow");
return false;
}
Give
return true;
if you want the onclick function to get executed.
If I have understood what you meant, this should do it:
__doPostBack should be called only after the animation is done, you can do it by passing a callback function to jquery's show's, second parameter.
UPDATES:
$(document).ready(function()
{
$("#lnkbtnUnitAdd").click(function (e) {
var btnName = $(this).attr('name');
$("#divUnit").show("slow",function(){
__doPostBack(btnName,''); //now call the actual postback event
});
e.preventDefault(); //prevent default postback behavior
return false;
});
});

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

JQuery ajaxStart event not being captured in ASP.net AJAX

I have an asp.net page with a save button within an updatepanel and contenttemplate. The save works nicely, but I am trying to add a "wait" gif while the save is happening using JQuery, but the ajaxStart event is not firing. I put a simple catch shown below:
$(document).ajaxStart(function () {
alert('starting');
}).ajaxStop(function () {
alert('done');
});
No alerts show when I click the save. Is there a problem when trying to capture ASP.net Ajax events, is asp doing some funky type of Ajax calls that can't be captured by Jquery?
Thanks, let me know if you have any ideas about this,
Mark.
The ASP.NET update panels seem to do their own thing... Tap into the PageReuqestManager and setup your own calls here...
EDIT
I simplified the functions a bit below to match your sample a little more...
<script type="text/javascript">
function pageLoad() {
if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(AjaxEnd);
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(AjaxBegin);
}
}
function AjaxEnd(sender, args) {
alert("I am done...");
}
function AjaxBegin(sender, args) {
alert("I am about to start...");
}
</script>

How to specify javascript to run when ModalPopupExtender is shown

The ASP.NET AJAX ModalPopupExtender has OnCancelScript and OnOkScript properties, but it doesn't seem to have an OnShowScript property. I'd like to specify a javascript function to run each time the popup is shown.
In past situations, I set the TargetControlID to a dummy control and provide my own control that first does some JS code and then uses the JS methods to show the popup. But in this case, I am showing the popup from both client and server side code.
Anyone know of a way to do this?
BTW, I needed this because I have a textbox in the modal that I want to make a TinyMCE editor. But the TinyMCE init script doesn't work on invisible textboxes, so I had to find a way to run it at the time the modal was shown
hmmm... I'm pretty sure that there's a shown event for the MPE... this is off the top of my head, but I think you can add an event handler to the shown event on page_load
function pageLoad()
{
var popup = $find('ModalPopupClientID');
popup.add_shown(SetFocus);
}
function SetFocus()
{
$get('TriggerClientId').focus();
}
i'm not sure tho if this will help you with calling it from the server side tho
Here's a simple way to do it in markup:
<ajaxToolkit:ModalPopupExtender
ID="ModalPopupExtender2" runat="server"
TargetControlID="lnk_OpenGame"
PopupControlID="Panel1"
BehaviorID="SilverPracticeBehaviorID" >
<Animations>
<OnShown>
<ScriptAction Script="InitializeGame();" />
</OnShown>
</Animations>
</ajaxToolkit:ModalPopupExtender>
You should use the BehaviorID value mpeBID of your ModalPopupExtender.
function pageLoad() {
$find('mpeBID').add_shown(HideMediaPlayer);
}
function HideMediaPlayer() {
var divMovie = $get('<%=divMovie.ClientID%>');
divMovie.style.display = "none";
}
If you are using a button or hyperlink or something to trigger the popup to show, could you also add an additional handler to the onClick event of the trigger which should still fire the modal popup and run the javascript at the same time?
The ModalPopupExtender modifies the button/hyperlink that you tell it to be the "trigger" element. The onclick script I add triggers before the popup is shown. I want script to fire after the popup is shown.
Also, still leaves me with the problem of when I show the modal from server side.
TinyMCE work on invisible textbox if you hide it with css (display:none;)
You make an "onclick" event on TargetControlID, for init TinyMCE, if you use also an updatepanel
For two modal forms:
var launch = false;
var NameObject = '';
function launchModal(ModalPopupExtender) {
launch = true;
NameObject = ModalPopupExtender;
}
function pageLoad() {
if (launch) {
var ModalObject = $find(NameObject);
ModalObject.show();
ModalObject.add_shown(SetFocus);
}
}
function SetFocus() {
$get('TriggerClientId').focus();
}
Server side: behand
protected void btnNuevo_Click(object sender, EventArgs e)
{
//Para recuperar el formulario modal desde el lado del sercidor
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", "<script>launchModal('" + ModalPopupExtender_Factura.ID.ToString() + "');</script>", false);
}
var launch = false;
function launchModal() {
launch = true;
}
function pageLoad() {
if (launch) {
var ModalPedimento = $find('ModalPopupExtender_Pedimento');
ModalPedimento.show();
ModalPedimento.add_shown(SetFocus);
}
}
function SetFocus() {
$get('TriggerClientId').focus();
}

Resources