ASP.net user control doesn't call a javascript function - c#

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.

Related

How would I let 1 .aspx page use another .aspx page's code?

I have 2 aspx files in my project. The first.aspx page has some content on it and when I click on a button, it will launch a frame (second.aspx that only has code to show a calendar) on the same page.
Now once that calendar(second.aspx) loads on first.aspx, I want to click a link on the calendar that will .show() a hidden DIV on the first.aspx page.
How do I access code cross pages? In other words, how can I write some code in second.aspx that will affect first.aspx.
What you're asking for is not really possible. You're probably approaching it the wrong way. What you should do is turn your calendar page into a user control so that it can be used seamlessly in first.aspx.
Here is how to get started with user controls in asp.net:
After you turn it into a user control there are different approaches to getting access to the properties of the user control from your page. Here is one approach using the FindControl method.
Hope that helps.
The easiest solution would be to show and hide your div with jquery. Simple give your div a class like:
<div class="myCalendarDiv" style="display:none" />
And your Button should look like this:
<asp:Button id="myButton" OnClientClick="return ShowCalendar();" runat="server" />
<script type="text/javascript">
function ShowCalendar() {
$(".myCalendarDiv").show();
return false;
}
</script>
Another way would be instead of creating a seprate webpage for the calendar, as proposed you can use a jquery dialog, or make a usercontrol and embedd it on the same page.
(Posted on behalf of the OP).
So since I was dealing with an Iframe, I found out that you can target the parent window which would be first.aspx.
I used "window.parent.MYFUNCTION();" to call my JavaScript function on first.aspx and show the div.

Calling codebehind method from markup and is throwing javascript error

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.

How to update an HTML control from code within SilverLight

How can I update a textbox or label (specfically an asp.net control) text property from the code in the silverlight control?
Suggested solution:
I suppose that you could try to do it in two steps:
write a javascript function that updates a control based on a given parameter, let's name it updateControl:
<script type="text/javascript">
function updateControl(newValue)
{
//update your control here with newValue parameter with javascript
...
}
</script>
in your Silverlight application (in the place you want to invoke the control value change) you should write:
HtmlPage.Window.Invoke("updateControl", "this is a new value")
Another solution for page update only:
If you just need to refresh the page to get the value from other place, you can write in your Silverlight code:
HtmlPage.Document.Submit()
In the postback, you could get this data and show it in the control.
References and useful resources:
ScriptObject.Invoke Method : http://msdn.microsoft.com/en-us/library/system.windows.browser.scriptobject.invoke%28v=vs.95%29.aspx
Walkthrough: Calling JavaScript from Managed Code: http://msdn.microsoft.com/en-us/library/cc221359%28v=vs.95%29.aspx
Silverlight and JavaScript interop basics: http://pietschsoft.com/post/2008/06/Silverlight-and-JavaScript-Interop-Basics.aspx
How to set the value of a form element using Javascript: http://www.javascript-coder.com/javascript-form/javascript-form-value.phtml
You can do it calling javascript function from silverligt.
Shortly it looks like this:
HtmlPage.Window.Invoke("globalJSMethod", stringParam);
Note that javascript method must be accessable from window - window.globalJSMethod(...)
Check this walkthrough to see in details how to do this.

Ajax removes any changes made my javascript

Using ajax I am causing an OnTextChangedEvent before this happens there is some Javascript that performs a check on the input field for validation and outputs some text based on whether it is valid or not. The Ajax I run resets the changes made by my javascript. It all happens in this order:
Javascript fires!
Text changes show
Ajax fires!
Text changes reset
The ajax partial autopostback is contained in an update panel. Without giving any code away is there anyone who has an idea of a way to stop the javascript changes resetting?
Over the day I will add code as I find time. Thought I would get the question up atleast. Thanks in advanced.
The Text changes are made in the DOM-Model and are not transmitted to the server.
If the ajax fires it will override the changes in the DOM made by javascript.
Solution is to transmit the validation-texts to the server and to add them again via ajax.
An UpdatePanel completely replaces the contents of the update panel on
an update.
This means that those events you subscribed to are no
longer subscribed because there are new elements in that update panel.
Full answer here
In your Page or MasterPage, put the following script
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function EndRequestHandler(sender, args)
{
Validate(); //method that performs check on input field
}
</script>

How do I generate JavaScript during an AJAX callback (postback) and then execute it on the browser?

In summary:
I have an ASP.NET web page that causes an AJAX postback to the server. When this event handler runs (in the code behind) it will generate some JavaScript that I then want to run in the client. Not sure how to achieve this.
In Detail:
I have an ASP.NET web page with multiple items displayed on the page.
As a "nice to have", I want to display either a green circle or a red cross next to each item (these differ depending upon each item). Since it isn't vital for the User to see these icons and also because it takes several seconds to work out which icon should be shown for each item, I want to perform this after the page has loaded, so in an AJAX callback.
My thought therefore was this. When creating the page, I would create both icons next to each object and create them with the style of "hidden". I would also make a note of each one's client ID.
Then, when the callback occurs, I fetch the necessary data from the database and then create a JavaScript function that changes the display for each of the icons I want to show from "hidden" to "visible".
I thought I could achieve this using the ScriptManager object.
Here's a very trivial version of my server side code (C#)
void AjaxHandler(object sender, EventArgs e)
{
// call to database
string jscript = "alert('wibble');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript);
}
Obviously, here I'm just trying to get an alert to fire after the postback has occurred...in real life I'd have my JavaScript function to change the display of all the icons I want to display.
When I run this, the serverside code runs and yet nothing happens in the server.
I have also tried:
ScriptManager.RegisterClientScriptBlock()
Page.RegisterStartupScript()
Page.RegisterClientScriptBlock()
Page.ClientScript.RegisterStartupScript()
Page.ClientScript.RegisterClientScriptBlock()
but none of them work....
FireFox shows the following JavaScript error:
Error: uncaught exception: [Exception... "Node cannot be inserted at the specified point in the hierarchy" code: "3" nsresult: "0x80530003 (NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)" location: "http://localhost/MyWebSiteName/Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=ctl00_RadScriptManager1_TSM&compress=1&_TSM_CombinedScripts_=%3b%3bSystem.Web.Extensions%2c+Version%3d3.5.0.0%2c+Culture%3dneutral%2c+PublicKeyToken%3d31bf3856ad364e35%3aen-US%3a3de828f0-5e0d-4c7d-a36b-56a9773c0def%3aea597d4b%3ab25378d2%3bTelerik.Web.UI%2c+Version%3d2009.3.1314.20%2c+Culture%3dneutral%2c+PublicKeyToken%3d121fae78165ba3d4%3aen-US%3aec1048f9-7413-49ac-913a-b3b534cde186%3a16e4e7cd%3aed16cbdc%3a874f8ea2%3af7645509%3a24ee1bba%3a19620875%3a39040b5c%3af85f9819 Line: 1075"]
Does anyone know if what I am trying to do is even allowed?
If not - what's my alternative?
Thank you
Since your script doesn't have enclosing <script> tags, you need to use this form of RegisterStartupScript:
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript, true);
You said your initial goal was:
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Here's a way you can do that:
given:
<asp:ScriptManager runat="server" ID="scriptManager">
</asp:ScriptManager>
<script type="text/javascript">
function endRequestHandler(sender, args) {
var dataItems = args.get_dataItems();
for(var key in dataItems){
if(/^javascript:/.test(dataItems[key])){
eval(dataItems[key].substring("javascript:".length));
}
}
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
</script>
<asp:UpdatePanel runat="server" ID="pnl">
<ContentTemplate>
<asp:Button runat="server" ID="btnClick" Text="Click me!" OnClick="btnClick_Click" />
</ContentTemplate>
</asp:UpdatePanel>
You can create a click handler that does this:
protected void btnClick_Click(object sender, EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterDataItem(this, "javascript:alert('hello world!');");
}
What's happening is during the postback, the page request manager is sent a data item your code-behind. That data-item happens to be a javascript command. After the postback, the client side script manager's endRequest handler is checking for data items. Normally you'd want to see who those items are for, which is apparent by the key of the item (it's the client ID of the control that is the target of the data being sent). In your case, you could load this up with the javascript that you want to fire, tell yourself that it's a javascript because it's prepended, then dynamically evaluate the script.
So in this example, clicking the "Click Me!" button will generate a Hello World prompt whose script was actually created by the code-behind during the postback.
You'll have to be very cautious with this approach until you're comfy - I'd avoid references to "this"...
Happy coding.
B
Okay
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Couldn't get that to work....
I got around this in the following way:
When the page loads, data is sent (AJAX) to the server. This processes the data and serialises the results updating a hidden text element, which goes back to the browser. Meanwhile, I have a JavaScript timer on the page that runs a JavaScript function that was generated when the page first loads. This function looks at the hidden text element. If that element has text (the result of the postback) then it shuts down the timer, deserialises the data and then works out how to update the page.

Categories

Resources