Passing param to the OnLoad in aspx page from a javascript? - javascript

I have this javascript
function myFunction(source) {
window.open(source, "Title", 'width=400, height=400');
}
and in c# code I call it by
HtmlPage.Window.Invoke("myFunction", source);
which opens up a aspx page and goes to its OnLoad function:
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
My questions are
how do I pass in parameters to the event args in the aspx page? or is that even possible?
and how can I pass these parameters from my c# code to the javascript?
I am still learning javascript so please explain.
Thanks,
Voodoo

You need to add a query string to the URL, such as http://server/path.file.aspx?SomeName=SomeValue.
You can access in in the C# server-side code by checking Request.QueryString["SomeValue"].

PageLoad happens on the serverside before the page has been sent down to the client's compter where the javascript is executed. Have a look at the asp.net page lifecycle It used to be one of our stock interview questions for web devs and it's amazing how many asp.net devs don't know it
SLaks answer is the easiest and most of the time will probably do you well, however you could always use an ajax operation to send some data back to the server and affect the page. This is more complicated but more powerful and leaves your URL looking nice and clean

Related

Get return value from JS code to C#

I want to get the answer of a window.prompt() alert box through the C# Code Behind file. It's just a one-liner of JavaScript code, so I thought I could even execute it from the Code Behind file. It doesn't really matter to me whether it's a <script> tag in the .aspx file or executed through the .aspx.cs file.
I thought of having the script executed (called from the C# part) and then having the return value assigned to a certain not visible field, but is there any better way to do it?
The obvious way would probably go something like this:
.aspx file:
<script>
function foo() {
document.getElementById('MyFieldID').value = window.prompt('Answer this question:', '');
}
</script>
.aspx.cs file:
////////////////////////////////////////////////
//MyFieldID.Text now contains whatever I want//
//////////////////////////////////////////////
What do you say? Is there any better way?
Better way is always opinion based. What I'd say is you have a few options, all depend on what you're doing. HTTP and ASP.NET provide us a few means of sending data to the server, there are 3 main ones before HTML5:
Query string
Form values
AJAX calls
If you're redirecting the user to a new page after they answer the prompt, you can just send them to yournewurl.aspx?promptAnswer=*whatever*
If you're doing a postback, then you can use a form value (this looks like what you're doing in your example). You can put an <asp:HiddenField> on the page and populate it from JavaScript before submitting the form.
If you need just the prompt response, but are not attempting to reload the page, you can make an AJAX call that sends the variable to the server (this still uses #1 or #2 to send the data, it just does it without reloading the page).
Which of those three options works best depends on your implementation. However, your solution should work just fine. However, since the control you'd likely be using to stuff the value into is a HiddenField it would be in MyFieldID.Value not MyFieldID.Text. The only other thing you have to deal with is if your MyFieldID is nested in some other controls (like a ContentPlaceHolder) such that the ClientID has naming containers pretended to it so it's really something like ContentPlanceHolder1_MyFieldID when accessed from JavaScript.

Modify an UpdatePanel by calling server-side code from client code

It's possible that there's no way to do this, but I figure I would ask. I'm relatively new to asp.net, having played with it for about a week now. What I have right now is a page that calls a web service, polls it until it's done (with progress displayed in an UpdatePanel), then hides the progress text and instead displays the result (a recursive list of files with some metadata) by creating a TreeView and adding it to the UpdatePanel. What I would like is for clicking a node in the TreeView to update a second UpdatePanel with extended information (obtained server-side) about the node that was just clicked on. I don't see any way to call a codebehind function by clicking a TreeNode, but I can call Javascript code by setting the node's NavigateUrl to "javascript:function([the full path of the node])".
At this point, though, I'm kind of stumped. StackOverflow is full of correctly-answered questions about how to call back into the codebehind from javascript (using a WebMethod, or equivalent), but apparently you can't call code that isn't static, which would mean I couldn't modify the page itself, or for that matter, access the session or page state. StackOverflow is also full of questions about how to have javascript request that an UpdatePanel refresh itself (__doPostBack()), but without any way to communicate to the server what was clicked on, the UpdatePanel wouldn't know what to display.
Thus, the question, which I'm hoping has an answer: am I missing some clever way to have javascript on the page trigger a server-side function capable of taking a parameter and using it to do a partial postback of a different UpdatePanel?
Thanks!
Actually it's quite straightforward. Just place a LinkButton inside of second update panel (it can have an empty text and thus be invisible), in JavaScript call client-side .click() method of that control, and in ASP.NET handle server-side OnClick event.

Run JavaScript After DataBind

I have a ASP.Net Repeater control with a Table inside it. Is it possible to run a JavaScript function directly AFTER I call MyRepeater.DataBind()? I've been trying different things, but nothing is triggering the JavaScript function.
Thanks
Databinding occurs on the server in a postback as part of the Page Lifecycle process. In other words, excluding partial-postbadks, at the time this happens any existing DOM in the browser is destroyed. A whole new page is constructed on the server and transmitted to the browser, so that a new DOM can be built and rendered.
What all that means is that you want to think in terms of running your javascript in the page's onload event. One way to make this happen is using the ClientScriptManager.
Javascript can be called from server side by using RegisterStartupScript and RegisterClientScriptBlock methods.
http://www.mindfiresolutions.com/Register-clientside-startup-script-from-serverside-code-286.php
No. The javascript isn't even going to render and run until the code-behind has executed and the page delivered to the client. So it won't matter if adding the script is the first thing you do in the code-behind or the last thing you do (or directly after the DataBind()).
When using the ClientScriptManager Class, look at your code behind and you'll see the dynamic javascript is added just before the ending </form> tag (although it still may be possible to accomplish what you want to do, just with a different approach).
Well I found a solution, not sure it's the cleanest way to do it, but for my application's context it works:
I ran the javascript code after a partial postback using: Sys.WebForms.PageRequestManager.getInstance().add_endRequest();
Again, not the cleanest but suits the needs I have.
Thanks for all your input

Calling VB.Net from Javascript

I am trying to call a VB.Net subroutine on my ASP.Net page via a function key. I have managed to detect the key press using a Javascript function and am now trying to call the VB.Net subroutine from Javascript. I have seen 2 methods proposed, but have had no success with either:
Using jQuery
Using Web Methods
1) With jQuery, I get an error message in the web browser that says PageMethods undefined.
I am using a ScriptManager with EnablePageMethods = “True” and have syntax “PageMethods.VBsubroutine() in the Javascript function, but it seems PageMethods is not recognised.
2) I have also declared the WebMethods as follows (for testing purposes):
<System.Web.Services.WebMethod()> _
Public Sub ToggleTestButton()
If btnTest.Text = “Alpha” Then
btnTest.Text = “Omega”
Else
btnTest.Text = “Alpha”
End If
End Sub
Some have suggested that WebMethods should be declared as
<System.Web.Services.WebMethod()> _
Public Shared Function xxx()
But I get an error with the control btnTest.Text being underlined. Something about having to create an instance of objects? The issue is with the Shared. Besides I’m not intending to get any output from the function, hence the use of Sub.
Some have suggested that it must be Public Shared Function. Please advise on why this is so or if there is another way of achieving the same.
The webmethod route has no access to the elements on the page, and unless I'm mistaken should only be used when one requires to execute a sub asynchronously.
The best way to do this in my opinion would be be to place a hidden button on the page, then from the js that detects the function call, click the button.
Do you want to call vb.net function on your asp.net server, when the user presses some key in his browser (client side)?
If yes, then you may try ajax.

Calling Java inside JavaScript Function

Please tell me if we can call java inside javascript function ?
<HTML><HEAD></HEAD><BODY>
<SCRIPT>
function getScreenDimension() {
<% System.out.println("Hiiiiiiiii"); %>
}
</SCRIPT>
<FORM>
<INPUT type="button" value="call Java method direct" onClick = "getScreenDimension()">
</FORM>
</BODY></HTML>
While the answer of "No" is technically correct based on the phrasing of the question. You may want to read up on AJAX. It is a way for javascript to make a request to your backend code (in this case Java).
Javascript is client side, meaning it is run by the user's browser. Java is running on your server. In order for the client side javascript to interact with the backend Java, you need to make a request to the server.
My question to you would be, "What are you trying to do, and what do you expect to see?".
You have to realize that there are two different execution contexts. The first is the JSP itself whose code is executed by the JVM on the server-side, and the second is the Javascript that is executed by the browser. So when the code goes to the browser, you'll see: So the System.out.println will cause Hiiiiiiiii to be printed to the server logs, but you won't see anything on the browser. In fact, the Javascript code on the browser will look like this:
function getScreenDimension() {
}
Which is not valid Javascript code. The code in the JSP is run before the Javascript gets run on the browser. So to "run" Java code, you need to make a request to your server either by posting the form or with an AJAX call. This will cause Java code in the appropriate servlet or controller, to run.
UPDATE
After glancing at your code, it appears that you want to call a Java method directly. This is not possible with your current code. You might want to read up on AJAX. This will point you in the right direction.
JSP runs on the server. It generates a document which the server sends to the browser. That is the end of the involvement of JSP in the process. The browser then parses the document and runs any JS.
You can include JSP in a script element, it just has to output valid JavaScript.
You cannot have JSP that runs in response to JavaScript, other then when JavaScript causes the browser to issue a new HTTP request (either setting location.href, submitting a form, adding an image, or using Ajax, etc)
I think you have lack of understanding of what is going on here. Anything in middle of <% %> is executed when the page is first requested. Anything in javascript is executed when the browser calls it. What you have will never happen and there is no way to make it happen. However, you can use AJAX to do something like this but that's a different question.
Yes, you can. Use JSP expressions <%= %>. Example:
<aui:script use="aui-datepicker">
AUI().use('aui-datepicker', function(A) {
new A.DatePickerSelect({
calendar : {
dates : [ '<%="1/1/1970" %>' ],
}
}).render('#myDatePicker');
});
</aui:script>
Yes, you can call Java from Javascript, both if you mean the Java-VM on the server and on the client; i assume you mean the client (the VM in the browser); take a look here:
http://www.apl.jhu.edu/~hall/java/Java-from-JavaScript.html
You can. In JSF you can use PrimeFaces' component p:remoteCommand, which would contain action method. Call that remoteCommand by its name from JS and the java method will get executed.
JSF Page
<p:remoteCommand name='rmt' action="#{bean.doWork()}"/>
In JavaScript
function callJava {rmt();}
Use JSP code
<%
// Respond to the application with 1) result, 2) update, and 3) updateid values
String result = "blablabla";
out.print(result);
%>

Categories