JavaScript in button onclick not working - c#

I have a webpage (ASP.NET C#) that has a button:
<asp:Button ID="btnHide" runat="server" OnClick="HidePanel" Text="Hide"/>
and I'm doing a JavaScript alert like:
public void HidePanel(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"Hello","<script type=text/javascript> alert('Hello') </script>");
}
If I modify the function to not have object sender and EventArgs e then I can call it from Page_Load, and it works fine, I get the alert.
As written above I expect to see the alert when I click the button, but it's not happening. I'm sure it's something obvious, but I don't see it.

Use OnClientClick instead of OnClick. And add a return false to avoid a postback on the page.
<asp:Button ID="btnHide" runat="server" OnClientClick="alert('Hello'); return false;" Text="Hide"/>

You could try using,
ClientScript.RegisterClientScriptBlock(GetType(), "nameOfScript", scriptString);
I'ved used that before in a click event.
edit:
I can't edit posts yet, but your code works fine for me as well.
And depending on the situation he might want to do some server side stuff as well on the click event, or build up the script dynamically.
Edit:
If you already registered a script with the same name, it won't run, eg.
Page.ClientScript.RegisterStartupScript(this.GetType(), "Hello", "<script type=text/javascript> var i = 0;</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "Hello", "<script type=text/javascript> alert('other hello') </script>");

You can remove the code to register the JavaScript code and instead do this:
<asp:Button ID="btnHide" runat="server"
OnClick="HidePanel" Text="Hide" OnClientClick="alert('Hello');"
UseSubmitBehavior="false" />
This:
UseSubmitBehavior="false"
will cause the button to fire the client-side script, and it will run the server-side code (post-back).

Related

OnClick Event Not Firing on Button Click ASP.NET

I have an asp:Button that is in a JavaScript dialog window. It has an OnClick event called DialogWindowButton_Click as you can see in the code below. The event is not firing and I have put breakpoints in the C# file and it is not even entering the function. I'm not sure why and have looked at other forum posts to try to figure this out. I have 1) deleted the button and recreated the button and OnClick event themselves (this didn't work), and 2) added CausesValidation="False" to the asp:Button tag. Neither avenue has worked. What I have is shown below:
<div style="margin:auto; width:100px; padding-bottom:15px;">
<asp:Button ID="DialogWindowButton" runat="server" Text="Save Entry"
OnClick="DialogWindowButton_Click" CausesValidation="False"/>
</div>
Then in the C# file, I have:
...
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DialogWindowButton_Click(object sender, EventArgs e)
{
DialogWindowButton_ClickHelper();
...
}
protected AddressBookEntry DialogWindowButton_ClickHelper()
{
...
}
...
I have the correct file for the CodeBehind tag as well as for the Inherits tag. In the C# file you can see that the original OnClick event calls on a helper function defined directly below it, but breakpoints in the top of DialogWindowButton_Click() aren't being reached. There are no build errors either. Could there be something else I'm missing? Thank you!
You need to set UseSubmitBehavior to false (default is true):
<asp:Button ID="DialogWindowButton" runat="server" Text="Save Entry"
UseSubmitBehavior="False" OnClick="DialogWindowButton_Click" CausesValidation="False" />
From Reference:
Use the UseSubmitBehavior property to specify whether a Button control
uses the client browser's submit mechanism or the ASP.NET postback
mechanism. By default the value of this property is true, causing the
Button control to use the browser's submit mechanism. If you specify
false, the ASP.NET page framework adds client-side script to the page
to post the form to the server.

call javascript from server

my button on server works on alertMsg() how ever doesnt work on playSelected()
my button on Html works on playSelected() and alertMsg()
anyone can figure out for me why?
javascript
function playSelected() {
var a = "Video/" + document.getElementById("TextBox2").value + ".flv";
jwplayer("mediaplayer").setup({
flashplayer: "jwplayer/player.swf",
file: a,
image: "jwplayer/preview.jpg"
});
}
function alertMsg() {
alert("testing123");
}
button in html
input type="button" runat="server" value="Click me!" onclick='playSelected()'
button in server
asp:Button ID="Button2" runat="server" text="call javascript" OnClientClick="playSelected(); return true;" UseSubmitBehaviour="false"
<asp:Button runat="server"
OnClientClick='playSelected(); return true;'
UseSubmitBehaviour="false" />
Make sure your java script is allowed on the clietn browser. Also do postbacks logic in your page_load event. I would rather create the Button on overriden CreateChildControls method of the page, and on overriden OnPreRender wireup my java script and register the script with ClientScriptManager method RegisterStartupScript. So that you can have nice page life cycle control.

How to make the button_Click event opens the page in a pop-up window in ASP.NET?

The question is simple but I can't find a simple answer to it! .. btw I'll need to pass a QueryString to the page to be open.
Any ideas ?
You can actually link a javascript code into .NET with C#, below is an example, you could replace with your info, and push the parameters.
Response.Write("<script type='text/javascript'>window.open('Page.aspx?ID=" + YourTextField.Text.ToString() + "','_blank');</script>");
You can append on the end of it ?Field=your value passing&nextField=another value.
Is the answer to do this in javascript. As you make the underlying page in asp.net, provide it with the javascript to catch the buttons onclick event and call window.open(URL)
It depends on what you're trying to do but the simplest is to use the OnClientClick property of the Button. Take a look at http://msdn.microsoft.com/en-us/library/7ytf5t7k.aspx, in particular the details bout this property a little bit down.
Basically you'd do something like
<asp:Button ID="Button1" Runat="server"
OnClientClick="ShowPopup();"
Text="Test Client Click" />
With the JS to do your popup
<script type="text/javascript">
function ShowPopup() {
window.open('ThankYou.aspx');
}
</script>
You can also do both an OnClientClick and an OnClick if you need as well.
<asp:Button ID="Button1" Runat="server"
OnClick="Button1_Click"
OnClientClick="ShowPopup();"
Text="Test Client Click" />
Code behind
protected void Button1_Click(Object sender, EventArgs e)
{
Label1.Text = "Server click handler called.";
}

Click Event of Hyperlink

How to find Whether a hyperlink is clicked or not in ASP.net C# in runtime?
I want to write code on like that
Response.Redirect("Default.aspx");
If you want to execute server code upon a click in a link, then you should use the ASP.NET control <asp:LinkButton>
This is just like a button and will allow you to hook up Server Side Events and at the end you can just redirect the viewer to any page.
You would attach either the event in the code behind, or in the ASPX / ASCX of your link in question like so:
<asp:LinkButton ID="linkGoSomewhere" runat="server" Click="linkGoSomewhere_Click" />
OR
linkGoSomewhere.Click += (linkGoSomewhere_Click);
With an event handler looking like so in your code:
public void linkGoSomewhere_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
HOWEVER
In this situation, you don't need a server side control to just send the user somewhere else. You just need a simple hyperlink:
Go somewhere else
if this HyperLink you can do it using javascript but if it is LinkButton you can do it inside onclick event
<asp:LinkButton ID="MyLnkButton" runat="server" onClick="MyLnkButton_Click" Text="Click Me!">
protected void MyLnkButton_Click(Object sender,EventArgs e)
{
Response.Redirect("Default.aspx");
}
The onclick server side handler can be added to achieve this.
<asp:LinkButton ID="LinkEditLine" runat="server" Text="Edit" onclick="lnkEdit_Click"/>
You can determine this with the Click event of the LinkButton

Javascript to code behind in c# asp.net

Hi im looking to find out after I do this:
c#
div.Attributes.Add("onclick", "return confirm_delete();");
javascript:
function confirm_delete()
{
if (confirm("Are you sure you want to delete this comment?")==true)
return true;
else
return false;
}
It pops up with a message box with yes and no if I press yes how can I add a function into my c# how can I call it?
If yes go to c# code behind
and add in confirm_delete
if yes was clicked
do this
I need it so when some one clickes yes I can (from code behind in asp.net c#) add in a method to delete from mysql database.
Just dont know how I refrence to the javascript
public static string confirm_delete()
{
return something (dont know how to)
}
How about this add a button with the clientside click event instead of adding it in the code behind. Check to see if the popup returns true. If you return false it should prevent the server side event from firing.
<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/* post back*/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>
protected void btnDelete_Click(object sender, EventArgs e)
{
//run your serverside code if confirm was pressed.
}
Your JavaScript will need to call a page on your server. This is typically accomplished with AJAX and a web service.
This page on MSDN has a good overview of what's involved.
If you're interested in using jQuery, this page has a simple example.
You may be able to use a PageMethod to call your codebehind function, check out the following link for an example
ASP.NET Ajax PageMethods
Wondering why you are using a div? Can't you use asp.net Button / LinkButton and limiting it's postback based on confirm value?
e.g.
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"
OnClientClick="return confirm('Are you certain you want to delete this
product?');">
</asp:LinkButton>
Reference.

Categories