Javascript for running code-behind code when a button is clicked - c#

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.

Related

Disable postback OnItemClick

I have a radRotator whit an OnItemClick method which is fired when the user click on one of the items while rotating.
In the OnClick method, I get the index of the item clicked and then I make use of it.
The problem is that every time that a click is performed in the radrotator, it stops and restart all over again. I suppose this is because of the post back generated by the OnItemClick.
How can I disable the post back on the OnItemClick but still fire the command?
<telerik:RadRotator ID="RadRotator1" RotatorType="AutomaticAdvance" ScrollDirection="Up"
ScrollDuration="4000" runat="server" Width="714"
ItemWidth="695" Height="260px" ItemHeight="70" FrameDuration="1" InitialItemIndex="-1"
CssClass="rotator" OnItemClick="RadRotator1_ItemClick">
OnItemClick will do a postback. I think you will have to call server side function from javascript. Since you are using telerik controls, you can use either RadAjaxManager or RadAjaxPanel to do the server side call.
$find("<%= RadAjaxPanel1.ClientID %>").ajaxRequest();
The above line will make a call to RadAjaxPanel1 ajaxrequest event.
Updated code -
<telerik:RadRotator ID="RadRotator1" RotatorType="AutomaticAdvance" ScrollDirection="Up"
ScrollDuration="4000" runat="server" Width="714"
ItemWidth="695" Height="260px" ItemHeight="70" FrameDuration="1" InitialItemIndex="-1"
CssClass="rotator" OnClientItemClicked="itemclicked">
<script type="text/javascript">
function itemclicked(sender, args) {
// you will have to make a server side call from here
// if you have RadAjaxPanel or RadAjaxManager on this page you can call ajaxRequest to //make server side call.
$find("<%= RadAjaxPanel1.ClientID %>").ajaxRequest();
}
</script>

Calling code behind method from Client

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
}

Using JQuery Modal Diaglog to fire a Server Side Control

OK so I have a jquery modal dialog. It accepts an input and then has an ok and and cancel button. Cancel works fine by simply closing the dialog. The ok button fires the OnClientClick when I really want it to fire the OnClick method so I can go into the server controls and log the input into the database using ASP.NET. Any ideas on how this is supposed to be done using jquery?
Side note: I'm not currently by the computer that has the code, but I'll try to update it as soon as I can.
You could try this:
Insert a ASP.NET button on your form, binded to the event that you want to trigger, then, with jQuery do $('#your_button_ID').click(); on the 'OK' event of your dialog.
Hope it helps!
In your codebehind create a static function and add the [WebMethod] attribute, so now you can fire code behind methods from Jquery.
javascript:__doPostBack('IDOfYourControlButton','')
This is the same method a button or linkbutton uses to fire the onClick event in .NET
Demo webmethod
in code behind you add this
[System.Web.Services.WebMethod]
public static string SayHi()
{
return "Hi";
}
in yr aspx file you add this javascript
<script>
function GetHi() {
PageMethods.SayHi(onComplete);
}
function onComplete(result) {
alert(result);
}
GetHi();
</script>
and dont forget to add this also in yr site.master or aspx page right under the
<form runat="server">
<asp:ScriptManager ID="scriptManager" EnablePageMethods="true" runat="server"/>
</form>

Refresh a button

protected void Button1_Click(object sender, EventArgs e)
{
}
My application contains a update button. when I click the button the browser must automatically refresh the page.
Is there any code behind code for button?
there is none. Doing so will create a postback on your page, and so will "refresh" your page, at least everything that was done in the page load event and in the prerender event.
In a updatePanel in ajax, it will create a callback. So that only the updatePanel will undergo the postback on the client side, whereas the whole page cycle will be run on the server side.
with server-side button control - you cant.
not sure what are you trying to achieve, but here's a JS workaround for the issue (using JS location.reload() to reload the page):
<input type="button" value="refresh" onclick="javascript:location.reload()" />
Here is one way to do it

Creating a clicked event on ascx control when pressed

I have a question about creating and managing events inside an ascx custom web control.
I have created a very stupid control consisting in a div containing a asp:Label control, it is a very simple structure:
<div id="mydiv" runat="server">
<asp:Label id="mylabel" text="Text"... />
</div>
That is, very simple.
I would like to add an event: clicked. I want to let the user add this control on the page and attach handlers to this event so that when this control is clicked it is possible to do something. It might seem a strange solution, it's like i'm trying to invent again the button control, that is: my custom button.
Well to fire the event I would like to add a javascript in my div and call a js function that calls, using ajax mechanism, a server side function.
Well how to call a server side function from here. I posted a question about how to call a server side function from a client side one and got some answers (many of them told me to use PageMethods), well it seems that pagemethod does not work, it compiles but when running and clicking on my control and executing the js (in the line PageMethods.mymethod()) here I have an error --> Java script exception: unrecognized method. It seems not finding the PageMethod.
Well, considering my objective, how can I do?
Ah, a solution like: use the click event in the label is not what I want because the click event must fire when I click in the div, consider that I might set a large padding so that a large empty space can provide a large clickable area.
Thanks in advance.
Create a Event in your User Control
E.g: -
public event EventHandler<CustomEventArgs> Click;
and a handler
public void OnClick()
{
if(this.Click !=null)
{
//what ever else you do
this.Click(new CustomEventArgs(...));
}
}
Also handle the mouse click (mouseleftbuttonup) on the User Control (and fire your event from there). i.e.
protected void OnMouseDown(...){ this.OnClick(); }
From the ASP.NET page, you can register the user control event and handle it:
MyControl.Click += new EventHandler<CustomEventArgs>(myctr_click)
protected myctr_click(object sender, CustomEventArgs e){
//do anything
}
PageMethods uses a web service within the page class; I assume you want a postback to the server and process this click in the page, right?
All controls that postback use a __doPostBack('clientid', '') method to postback to the server. Your label would need to do the same. Within the control, the control needs to implement IPostBackEventHandler to process these events, and raise the click event.
Check out this example: http://www.myviewstate.net/blog/post/2009/05/14/Implementing-IPostBackEventHandler-in-an-ASPNET-Control.aspx
I may have misinterpreted your requirements, but can't you just wrap the div in an asp:linkbutton?
<asp:LinkButton ID="lnkSomething" runat="server" OnClick="lnk_something_Click">
<div id="mydiv" runat="server">
<asp:Label id="mylabel" text="Text"... />
</div>
</asp:LinkButton>
and then on the server side:
protected void lnk_something_Click(object sender, EventArgs e)
{
}
As yellowfrog mentioned in the comments, you could then extend this by further wrapping it in an update panel for an async postback.

Categories

Resources