Apparently it is a very simple problem. I have a button on an ASPX page:
<input id="ok" type="button" name="ok" value="OK">
When this button is clicked, I want to call a method in code behind and do a postback afterwords.
What I have found so far is using __doPostback etc. but also came to know that Microsoft is moving away from it. Maybe ClientScriptManager.GetPostBackEventReference can work too but I am not sure how it can be done.
I cannot use an AJAX call from jQuery because of some restrictions.
You can use in you aspx markup:
<input id="ok" runat="server" onserverclick="btnOk_ServerClick" type="button" name="ok" value="OK">
and put this code in aspx code behind(.cs) file:
protected void btnOk_ServerClick(object sender, EventArgs e)
{
}
Just put runat="server" tag on this input then you can access it on code behind
Update: if you wanna call a method look at this samples. this and this
You could alternatively call an http handler. You could also implement a web service of some kind, either REST or SOAP.
Each of the above could be called using a javascript event (for example onclick) registered on the specific html button, out of ASP.NET page lifecycle. For example you could call this function on the onclick event (targetURL would be replaced by the URL of http handler, or the respective service):
<button onclick="httpGetRequest('targetURL')">Click me</button>
function httpGetRequest(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
Hope I helped!
If you are able to generate asp:button then it will be easy for you . You can add event handler to you button generated dynamically. ie)
btnClick.OnClick += new EventHandler(btnClick_Click);
Protected void btnClick_Click(object sender, EventArgs e)
{
// code goes here
}
Related
How to you code an <a href="... tag in ASPX to call a simple code behind function?
I have inherited a bit of code. I did not write this originally but I am trying to modify it.
In the steppayment.aspx file there are lots of "<a href..." tags that target either a whole URL or another aspx file.
But what if I only want to call a function in the code-behind, steppayment.aspx.cs?
In the aspx file, steppayment.aspx, I have this line of code:
<u><b><a href="fsModifyVisualContentonPaypal();" >Click here</a></b></u> now to open the PayPal payment window.
In the code behind, steppayment.aspx.cs, I have this line of code:
protected void fsModifyVisualContentonPaypal()
{
fsCreditCard.Visible = false;
fsAfterCreditCard.Visible = true;
}
I have break points in this function. It never gets here. When the user clicks on the "click here" it throws an error.
Use a LinkButton control instead of a basic HTML anchor tag
<asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server" Text="Click here" />
To call client side methods like javascript you would use OnClientClick. You'll want to check out the documentation for LinkButton on MSDN
If it you want it to work on postback, try an ASP.NET LinkButton control.
This is from memory, but it would be something like this:
<u><b><asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server">Click here</asp:LinkButton></b></u>
If you want it to work without a postback, that gets you into either Ajax territory or plain JavaScript. (Or, you might look up the ASP.NET UpdatePanel.)
All of this is assuming that you're using ASP.NET WebForms. If you're using MVC, that's another topic.
Both answers would work. You need to change the event method signature as well like this:
protected void fsModifyVisualContentonPaypal(object sender, EventArgs e)
{
fsCreditCard.Visible = false;
fsAfterCreditCard.Visible = true;
}
And your link button should look like this ( as suggesested by both answers):
<u><b><asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server">Click here</asp:LinkButton></b></u>
I am needing to use the same form for displaying multiple things and I realize that when I add links like:
A
it has the same form and web address, but with a #A at the end of the address.I thought I could use this for displaying multiple things on the same form. My idea is to have C# code in the page_load method to detect what the web address is and use a conatins method for the url string and detect if there is #A to change the content of the form. Here is an example:
C# code:
protected void Page_Load(object sender, EventArgs e)
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
if(url.Contains("#A"))
{
div1.Visible = false; //content 1
div2.visible = true; //content 2
}
}
asp.net code:
A
<div ID="div1" runat="server">
content 1
</div>
<div ID="div2" runat="server">
content 2
</div>
I have tried to put the Page_Load method in a script tag, but still didn't work. I guess since the url is different the cs code is not valid? I know it goes through the page_load method once, before I click on the link. Also I do use a method that gives me the controls of div1 and div2, so that is not the problem. I thank everyone in advance for your help! Also if my way is not the way to do the job then please tell me any way possible to achieve what I am trying to do.
edit: I can't use a button to replace a link... maybe a asp:hyperlink?
That's an HTML hyperlink you're using and it won't cause a postback thus page_load will never get called when you click it.
I would suggest if you want to show an hide divs that you use client side JavaScript. Alternatively you could (for example) use an asp.net button control which will cause a postback.
I would suggest scrapping the anchor with an href approach in favor of this:
Use the ASP.NET server controls, along with their click event handlers to manage the visibility of controls on your page.
In your Page_Load, make it so the page has an initial state of showing controls, like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
div1.Visible = false; //content 1
div2.visible = true; //content 2
}
}
Now instead of an anchor tag, you can use an ASP.NET Button or LinkButton to cause a postback to the server, like this:
<asp:Button id="Button1"
Text="Click here to change page to B"
OnClick="Button1_Click"
runat="server"/>
Now you have the event handler code which would change the visibility of controls, like this:
protected void Button1_Click(Object sender, EventArgs e)
{
div1.Visible = true; //content 1
div2.visible = false; //content 2
}
I am currently working on asp.net using C# and I need to show a message box and confirm the input from user and redirect to another page, my code is something like this:
protected void Button1_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>");
sb.Append("if (confirm('YES OR NO?')){ /*some javascript code*/ }");
sb.Append("</script>");
Page.RegisterStartupScript("FocusScript", sb.ToString());
Response.Redirect("Default.aspx");
}
here the problem is directly getting redirected to next page without showing message box.
if i remove Response.Redirect("Default.aspx"); it shows message box successfully. I think the here may be is Response.Redirect() has higher precedence compared to javascript
I tried using
sb.Append("if (confirm('YES OR NO?')){ window.location.href = \"Default.aspx"; }\");
instead of using Response.Redirect() but page didn't got redirected, what should I do to resolve this problem?
Do you absolutely need to handle this on the server side? Indeed this is where quite a simple thing is getting confusing.
If you could, for instance, handle it with Javascript / jQuery, you could do something simple like:
$('#Button1').click(function(){
if (confirm("Yes or No?")){
window.location = "/default.aspx";
}
});
There is an option of using adding javascript in client click event
eg:-
<asp:button id="Button1" OnClientClick="javascript:return confirm('Are you sure?');" runat="server" onclick="Button1_Click" />
and then in the code side simple redirect the page.
Confirm is a JavaScript function and it executes on client side. After you register it, you immediately redirect to another page, and so the function is never executed.
add following code on Page_Load
Button1.Attributes.Add("onclick", "if(confirm('do you want to redirect?')){}else{return false}");
now ur button click will first trigger java confirmation modal box.
as for ur Button1 click
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
The idea is - your codebehind Button1_Click event will be triggered only after user confirms by clicking OK
I think it is better to add an attribute to the button at page load and leave the button_click function to just redirect. Something like this (Page Load):
button.attribute.add("onclick","Javascript:confirmFunction();")
in button click just have this:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
finally in JS have this:
<script>
function confirmFunction()
{
if(Confirm("Yes OR NO")
//Add your JS Code
return true; //will pass onto server
else
//Add your JS Code
return false; //will not go to server
}
</script>
HTH
I Have a small working application on ASP.NET and C# and I would like to add some Javascript to it.
I know that for example I can use the Confirm button and then do something on yes or no.
What I would like to do is call some of the functions I have in the code-behind, depending on the answer to the Confirm Button.
How do I go about this?
Many Thanks!
Simple.
Put a hidden div on your aspx page that contains button triggers to your methods:
<div style="display: none">
<asp:Button ID="TriggerMethod1" runat="server" />
</div>
In your javascript, in the confirm part of your code simply do:
__doPostBack('TriggerMethod1', '');
And in your code-behind, handle up that button click to call Method1.
I would create an ASHX handler file and post back to the hander using jQuery ajax methods.
See an article on this here:
Using jQuery in ASP.NET apps with httphandlers
To call a server side method on a client side event you need to do the following:
1- Create the server side method:
void DoSomething(...) { ... }
2- Implement the System.Web.UI.IPostBackEventHandler.RaisePostBackEvent which take one string argument (You can assign the name to the value of this argument).:
public void RaisePostBackEvent(string eventArgument)
{
DoSomething(...);
}
3- Write a script to trigger post back:
function TriggerPostBack(control, arg){
__doPostBack(control, arg);
}
4- Call the PostBack trigger function when needed:
<a .... onclick="TriggerPostBack('control', 'arg')" .. />
Have you tried to use the search first in the site!!
Call ASP.NET function from JavaScript?
Calling functions from an ASP.NET code file with javascript
or https://stackoverflow.com/search?q=Call+C%23+Functions+From+JavaScript
i have a popup that is getting displayed when Save button is clicked. The popup has 2 buttons. Yes and No. No should cancel the popup
and yes should take you to function in the code-behind say, btnSave_Click(object sender, Eventargs e). How is it possible. Could someone help me, i am new to Javascript.
Below is the code where i am showin the popup.
var mdlPopup = $find('<%= ModalPopupExtendersavechanges.ClientID %>');
if(mdlPopup)
{
mdlPopup.show();
}
To do this you will need to set your server side function as a web method like this:
Add to the top of your code behind:
using System.Web.Services;
using System.Web.Script.Services;
Then decorate your method with these attributes:
[WebMethod(), ScriptMethod()]
public static void btnSave_Click(Object sender)
{
//Stuff
}
To call this from the client side (Javascript) do this:
PageMethods.btnSave_Click(this,btnSave_Click_Finished);
You can place that in a client click event. The first argument is the sender parameter, the second is the javascript function to call when the server side method has completed.
You can't call server side code from JavaScript directly. Make a postback or fire a XHR (AJAX) request in the background.
I think it is possible for you to acess the serverside script by using javascript.
__doPostBackis a function which is behind the asp postback and this function is called when a button is clicked or dropdown value is changed.
For more details pls refer to [this.][1]
All you need is to place a <asp:Button ID="btnSave" runat="server" onClick="btnSave_Click" /> in the form and in the javascript (ie button click function) just call the __doPostBack('<%= btnSave.UniqueID %>', '');
So it will calls the serverside function.(btnSave_Click)
Notice that you need to give '<%= btnSave.UniqueID %>' as the firstargument.
The above will works as similar to a server button click
The another way is to make a post or ajax using jquery.post or jquery.ajax it is possible to send request asynchronously to the server.Here you want to pass some query string and call the appropriate function in the page_Load
This will do without any postback
One another method is to use PageMethods from clientside by defining a static WebMethod
[1]: http://msdn.microsoft.com/en-us/library/aa720099%28vs.71%29.aspx/"Call serverside function from clientside"
I hope any one of these will solve your problem
the Yes button should be an asp.net control with a server-side handler
markup
<asp:button id="yesButton" runat="server" onclick="yes_click" />
codebehind
void yes_click(object sender, EventArgs e) {
// TODO your thing here.
}
the other buttons can be standard html inputs with javascript event handlers. if you are using javascript to alter element style, the changes won't persist across a postback- when the yes button submits and the page reloads, the popup won't be visible.