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.
Related
I have a C# application that uses WebForm. I am using the WebForm to display my application content (HTML / JavaScript).
My question is how do I communicate between them (API)?
Example: I like to minimize the program by using HTML buttons, etc....
If you have a web browser control on top of a normal control you could use the navigation event. E.g. make a link like:
Minimize
And in the navigation event of the browser control (I don't know how the event is actually called - just an example):
public void browser_OnNavigate(object sender, NavigateArgs e)
{
if (e.Target == "#MinimizeWindow")
// minimize and cancel event
else
// navigate to target
}
Local or Remote WebForms Application
You can use AJAX if you are trying to communicate with an external (or local) application.
Local WebForms Application
If by "application" you are actually referring to the back-end (code-behinds, etc.) of your WebForms project, then the other thing to look into are "server tags," otherwise known as "bee-stings." Here are just a few exsamples:
<% %>
<%-- --%>
<%# %>
<%= %>
Additionally, you can use event handlers for things like server-side button or anchor clicks, dropdownlist value changes, etc. You can make standard HTML controls server-side by adding the runat="server" attribute, or you can use .NET's WebControls (though they will still have to have the runat="server" attribute). Examples of these would be:
Front End
<button runat="server" onserverclick="btn_click">Click me</button>
...
or
...
<asp:Button runat="server" OnClick="btn_click">Click me</asp:Button>
Back End
protected void btn_click(object sender, EventArgs e)
{
...
}
I have a div tag that has a click event and the method I'm trying to call is from the codebehind.
This is my div tag
<div class="DivA" runat="server" id="ThisDiv" onclick="<%ClickMe();%>"></div>
The method is a simple
public void ClickMe()
{
Response.Redirect("www.google.ca");
}
I'm just testing this before I add the real stuff to it. The error that it is throwing is...
JavaScript critical error at line 16, column 49 in http://localhost:24307/DIVPAGE.aspx
SCRIPT1002: Syntax error
this is the line that it is giving me
<div id="ThisDiv" class="DivA" onclick="<%ClickMe();%>"></div>
I have tried changing the
<%ClickMe();%>
to
<%=ClickMe()%>
But that throws the same error. Another thing I don't understand is when you look at the line with the error that it is missing the runat tag and has added other characters to the onclick event.
Thanks
You have a concept problem here, do this, and test it will work:
<asp:LinkButton id="lbClickMe" runat="server" OnClick="ClickMe">
<div class="DivA" id="ThisDiv">
The Click Me Button!
</div>
</asp:LinkButton>
That's it, when runat=server is specified ASP.NET page parser will process the element as server side, so for this elements/controls no server tags in markup are allowed except data binding tags inside control templates. So to call you method you have to put a runat server on a control that haves the Click event, this is the case of the LinkButton, inside of him you can put your div for some specific styling of your UI.
Also not that, if you really want to have the your div behaving like that, there is no problem in complicating what is simple, but in that case please do this instead:
<asp:LinkButton id="lbClickMe" runat="server" OnClick="ClickMe" Visible="False"></asp:LinkButton>
<div class="DivA" id="ThisDiv" onclick="<%= Page.GetPostBackEventReference(lbClickMe) %>"></div>
The GetPostBackEventReference extracts the javascript code necessary to simulate your link button click, but once more is preferable to use directly the link button if you can.
Hope it helps,
Regards.
The <%= %> syntax emits a string, it doesn't do anything, like a redirect.
You need to do your redirect client-side with this javascript:
window.location = 'http://my.url.com';
If you need to interact with server side code, you need to do so with AJAX communicating to a web service to get the URL you need, and then performing the redirect described above.
Update
Sorry lads, brain freeze.
Yes, indeed, you can inject a string that will be evaluated as a click handler, but the handler must be a javascript function, not a server-side one! Once the page is rendered, it can no longer interact with the server save for communicating with a web service (or if we want to get technical, web sockets as well).
You can't call server-side C# methods from the DOM like that. You can only call JavaScript functions in an HTMLElement's onclick handler.
It is correct that you can call server-side methods using the template language, however this will be executed at the time of rendering the page; you could, for example, render the results of that server-side method, but you can't use a server-side method as a handler for a client-side event. The onclick event on a DOM element can only call a JavaScript function.
ASP web controls also have an OnClick event attribute, which is probably what's confusing you; this is different from the onclick event attribute on DOM elements (ASP will create additional code for its web controls, e.g. in case of an asp:button). This works using ViewState and a postback to the server. The onclick event for a DOM element however won't do those things for you.
Adding runat="server" will convert your element to an ASP control, however it will only be an HtmlControl. In the case of a <div>, it will be an HtmlGenericControl which simply writes out the onclick attribute of your element as it is.
So in ASP.NET I would simply do this:
<asp:ListBox OnSelectedIndexChanged="UpdateModels" runat="server" > </asp:ListBox>
But my listbox is inside an .ascx file. which is registered and included in my actual webpage massupdate.aspx like this
<%# Register TagPrefix="mass" TagName="make" Src="~/DynamicData/Make.ascx" %>
<mass:make id="makeControl" runat="server"/>
and in my make.ascx.cs I have this
public ListBox getlistbox()
{
return DropDownList1;
}
So I have access to the original listbox, but I don't know how to replicate the first code snippet in C# in my codebehind for mass.update.aspx .
First of all, the event registered in the ascx should fire even though it is registered as a control onto the page. Events should bubble up (or maybe down?) through all of the controls on a page, that's part of the "magic" of webforms.
Secondly, if you do need to set an event handler in code, you can either google "add event handler .NET control" or you can type something similar below and Visual Studio intellisense should auto complete it for you after you type the "+=" and you can take it from there.
makeControl.getlistbox().OnSelectedIndexChanged += this.Index_Changed
void Index_Changed(Object sender, EventArgs e) {
// whatever you need to do on the event
}
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.
i have save button in around 150 pages. when ever the user clicks on save button i should disable the button after the click. so that user does not keep clicking on save button again.
protected void Button1_Click(object sender, EventArgs e)
{
// right now once the user clicks the save button
Button1.Enabled = "false"
}
right now i am doing like this. is there any better solution u can provide me to improve codeing here would be great.
thank you
I think the best option to accomplish this is using javascript. If you are using jQuery (which I can even start to recommend enough) then you can put the javascript in your masterpage. You just need to find a way to create a selector for your save buttons. Like this:
$(document).ready(function(){
$('.saveButton').bind("click", function(e) {
$(this).attr("disabled", "true");
return true; //causes the client side script to run.
});
});
In this example, I assumed that all the save buttons would have the css class ".saveButton", but you can find your own way to select the button.
Cheers!
You can also try disabling it via Javascript.
You need to use JavaScript to alter the link once it's clicked to prevent future click handling, before allowing the page to proceed with the postback. A naive attempt would be,
<asp:LinkButton runat="server" id="button" OnClientClick="this.href='#'">
Click - doesn't quite work
</asp>
This successfully prevents successive clicks from triggering the postback, but it also prevents the first click from triggering the postback. A little more logic is required to make this work correctly. In the codebehind, I grab the actual postback JavaScript snippet and work it into some logic.
protected void Page_PreRender(object sender, EventArgs e)
{
button1.OnClientClick = string.Format(
"if(this.getAttribute('disabled')) return false; {0}; this.setAttribute('disabled','disabled'); return false;",
Page.ClientScript.GetPostBackEventReference(button1, null));
}
In the HTML template:
<asp:LinkButton runat="server" id="button" >
Click - does not allow multiple postbacks
</asp>
You can spruce this up with some CSS, and at that point I would advise including jQuery, so your code is more concise (due to its command chaining).
What you have to do is use some JavaScript and disable it when its clicked on the client side.
That click event fires on a postback.
Simplest way of attaching javascript to disable the button after user click would be this (in page onLoad event):
myButton.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";");
But if button is repeated on many pages, you can maybe create nested master page and put save button there, or inherit you page from class that implements this disable functionality. Also, you can "scan" for control you want to disable after click!