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.
Related
How can I retain client side html controls on postback? I have tried setting enableviewstate="true" but that did not work. A workaround I've done was to build a server side function that takes all the posted values and resets them via ClientScript.RegisterStartupScript and call this on every postback method. Is there an easier and more time efficient way of doing this?
You have have html control to keep their values on postback by making them runat="server" e.g.
<input type="text" id="txt1" runat="server" />
You need to create the controls at every postback. If you're looking for something a little easier to implement, take a look at the DynamicControlsPlaceholder control. It's a nifty little control that takes away most of the pain associated with persisting dynamic content.
Can you use HiddenField?
Now on clicking any button at client side, Preserve the data in HiddenField.
Use JQuery document.ready function to set the value again from HiddenField again. JQuery docuemnt.ready will be called on each Postback.
iv'e got an asp button which performs another task besides postback
i have done this by adding javascript code to the button as follows
if( !IsPostBack )
btn1.Attributes.Add("onclick", "f();");
i'm not sure of 2 things
the first :
where in the cs code i should add the function f() , currently i'm doing it in page load
while ignoring postbacks because then the function would have already been added(i might be wrong)
the second :
is there any to make the function execute only if the page was validated ? (after postback)
thanks in advance
eran.
I would use OnClientClick instead of adding the click event throug the attributes. As for your JavaScript, I would add it in the ASPX part. Depending on what the function does, you might be able to avoid the code behind all together and do something like this:
<asp:Button ID="Button1" runat="server" Text="Hi" OnClientClick="javascript:return f();" OnClick="Button1_Click" />
From your f() function, kick off the validation, and return true if validation passes, otherwise return false. If OnClientClick returns true the page will post back, and if it returns false the page will not post back.
1st Question
You will need to add it each time.
btn1.Attributes.Add("onclick", "f();");
2nd Question
You can check the validity of a page by checking the Page.IsValid Property
Unobtrusive JavaScript
If you're serious about javascript then you don't want to write inline javascript.
You will want to create an event handler in javascript code inside the script tags or in a external file.
If you're using .NET 4 server control id:s will be good, else I would use jquery's
contains selector. Search for the given server control ID.
I am developing asp.net web application, I have a repeater that call a registered user control, I have in the user control a button that I want to call a javascript function that make Ajax call to do some action on server. this button doesn't call the javascript method, I don't know why? and when I view source I found the javascript function is repeated for every item in the repeater, how to eliminate this repetition specially that I read server items inside the function, and why the function is not called?
Thanks a lot!
sercontrol.ascx
<div id="divBtnEvent" runat="server">
<input type="button" id="btnAddEvent" class="ok-green" onclick="saveEvent();" />
</div>
<script type="text/javascript">
function saveEvent()
{
var eventText = document.getElementById('<%=txtEventDescription.ClientID%>').value;
// make ajax call
}
Problem 1: In view source I found the javascript function is repeated for every item in the repeater.
Solution:
Put your js function on the page on which the user control is being called. You also have to place your js files references on your page not on user control.
Problem 2: You are trying to get control's value as <%=txtEventDescription.ClientID%>.
And I think, this control is on user control.
Solution: Please check your page source code and see that the control's actual clientid is.
If still have issues in calling js function, check firefox's Error consol.
Hope this help.
OP said and when I view source I found the javascript function is repeated for every item in the repeater
to get rid of it put ur javascript as follows
<head runat="server">
//heres goes ur js
</head>
I guess that's ur problem
Replace the saveEvent function definition from user control onto the page where the control is used. All the way as I understand, you have use in this function textbox id from that page.
Actually, if you have place javascript block in user control's markup it will be rendered along with the rest control's markup. To avoid this you may register javascript from the server code and check is that code block is already registered.
By the way, as it is - only the last function definition being taked into attention as it redefined the previous one each time new control instance rendered.
in my application i have the playvideo page where video will play, below that i have the option for sharing the video like adding to favorite ,playlist and sending mail.
when i click on any of the link the page is postbacking and video will start from the first.
i place update panel for link button even though it is not working (video is playing from the first i.e., page is postbacking. can u help me. thank you
Actually, the part of page that is within the UpdatePanel does the postback. Make sure you have only those controls(for instance, your links) inside the UpdatePanel.
Alternatively, you can use multiple UpdatePanels; for instance one for your video and one for the links. In this case note that, when one UpdatePanel gets updated other UpdatePanels also gets updated, which you may not want; so all you have to do then is to mark the UpdateMode property to Conditional and call YourDesiredUpdatePanel.Update() method manually - whenever required.
Btw, updating selected portions of the page also reduces the load on the server
Or you may want to look into using client callbacks instead of a postback. But since client callback uses XMLHTTP, which means Microsoft implementation of AJAX, therefore callbacks are just awesome as long as your are working with IE.
You might want to try taking advantage of Page Methods to do the work you need done server side.
http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Also, if you want to prevent a control from posting back, you can add return false to the end of your javascript onclick event on the control.
For example, if you had an asp button you were using you could do this:
<asp:Button ID="myButton" runat="server" OnClientClick="DoThingsInJavascript(); return false;" />
Or if you were just using a standard button you could say:
<input type="button" onclick="DoThingsInJavascript(); return false;" />
I've never really liked the update panel and I have sometimes found it's behaviour awful. Have you thought of trying something like a proper ajax call from Javascript
This question is an extension to Showing/Hiding div.
As stated, I found a workaround to prevent a Collapse panel from flashing upon load.
My solution was this:
In header:
function showDivs() {
divMenuContent.style.visibility = 'visible';
divMenuContent.style.display='block';
}
</script>
and panel hidden in div as:
<div id="divMenuContent" style="visibility:hidden; display:none;">
<asp:Panel ID="pnlAddNewContent" runat="server" CssClass="collapsePanel" Width="500px">
</asp:Panel>
</div>
and body load is
onLoad="javascript:showDivs();"
The thing is, it works perfectly on a blank page. But I think when I do a
ClientScript.RegisterClientScriptBlock(this.GetType(), "", sb.ToString());
it doesn't work - as in the panel doesnt collapse/show. The above code does work.
Do you believe the clientScipt conflicts with my javascript to show div? I don't receive any Javascript run errors within browser.
More info: The clientScript is called if its not a postback. I have also tried to call the javascript from the clientscript by adding the following code at the end of it:
sb.Append("\n}\nshowDivs();</script>\n");
But this time I get the following error:
divMenuConent is undefined.
ANy solutions?
If I remember right the RegisterClientScriptBlock injects its JS into the head. Could be that its injecting it above your code. Now that could mean a couple of things depending on what that injected code is doing.
Is it referencing any elements straight away (remember this is in the head so you won't be able to mess with the DOM as it would have loaded it yet, all that stuff needs to be after onload)
Is it referencing divMenuContent which you might only be declaring below it
Is it throwing an error which is stopping the rest of your inpage JS from running.
Use firebug in Firefox to double check you are not getting any funny JS errors and view the source and double check you are not trying to reference anything before you should be.
Also I'd suggest you look into using one of the JS frameworks to allow you to wire up multiple onload events so you don't run the risk of over-writing any previous attached events. This allows you to run multiple function when the page loads (or even better, aka faster, when the DOM loads). I'd suggest MooTools in which case you can do something like this
// You can add as many of these as you like and they will all run :)
window.addEvent( "domready", function() {
// Code to run goes here
});
You can use RegisterStartupScript for this kind Requirement.