How to execute jquery script before page load? - c#

I need to execute javascript before Page load in ASP.NET application.
My function returns user location, and I would like to pass value to server side and load data based on location.
The problem is javascript function executes after page load.
Here is my code:
$(function () {
getLocation();
});
in getLocation function I set hidden field value
$("#<%= HfLocation.ClientID %>").val(location);
in code behind I try to get value but it's always empty
protected void Page_Load(object sender, EventArgs e)
{
var location = HfLocation.Value;
}

I need to execute javascript before Page load in ASP.NET application
This requirements makes no sense. Remember how ASP.NET works:
A user request hits the web server
The web server dispatches the request to ASP.NET engine.
The ASP.NET engine instantiates the page and goes through the entire page lifecycle.
The page is rendered as HTML and is sent to the client
The client browser builds the DOM, runs client side javascript, ...
You see that it is impossible to have step 5 execute before step 3 (in which the Page_Load event executes).

I need to execute javascript before Page load in ASP.NET application.
In that case, you will need to make two page requests. You can't do it with a single page request, since Page_Load() runs before the HTML+JS is even sent to the client.
Instead, have a mini-page that makes the JS call and then either does a postback to the current page, or (probably better), loads a new page. You can pass the location data either through a regular (non-server) form, or perhaps by setting a cookie from JS on the client, or encode it into the query string.
The second page/request will then have the data you need when it's Page_Load() event fires.

Do an ajax callback using javascript to request the data.

Related

Adding response header after Page load

I am working on a legacy service that has 30 aspx pages with years of business logic
There is a parent aspx page which acts as a base page that the above aspx pages inherit from.
I need to add a Response header and I am having trouble finding the right place to add it to the ParentPage.aspx.cs so that it gets applied to all aspx pages.
Ideally I would want to add after PageLoad() is done for the the data to be available to add to the header.
I tried using the onPreRender() and onLoadComplete() stages to add the header. But it is not guaranteed that this would get called because the aspx pages have logic that do Response.Redirect() Because of the redirect onPreRender() and onLoadComplete() do not get called. I would not be able to change the logic on redirects
However UnLoad() does get called all the time. But response cannot be altered in the UnLoad() stage
Are there any suggestions where the header to the response could be added in the ParentPage.aspx.cs ?
Do you have a master page?
Just drop in the code to add a header in the page load event.
I mean, code can fill out text boxes, change things, and then you can toss in a new header - the order of such events don't matter.
So, if you have a master page that all pages use?
Then do this in site master:
protected void Page_Load(object sender, EventArgs e)
{
Response.AddHeader("Test", "My Test Value");
}
So, it not clear if you have a master page, but page load triggers in site master each time any navigate to any page occurs. And also the above runs each time any post-back or button click occurs on any page.
So, just add the header in the page load in master.
The above thus results in this:
So, it don't matter if you add the header at the start of code, or end of code say in a page. The other code behind can run, make changes to the "DOM" via code behind, but everything WAITS 100% until ALL of the code behind is done running, and THEN and only THEN does the WHOLE page make the trip back down to the client side, the client side re-loads the page, re-starts any JavaScript code (and re-sets, all JavaScript values and variable to fresh start), and then the page life cycle is complete, ready to start again on the next button click etc. And on the server side, the page class is disposed, and all its variables etc. also goes out of scope (hence the term state-less). So, both ends, including client side js code variables are re-set in this process.
So, in fact the "order" or what event you use to inject/add that header? it really don't matter when it runs, only as long as it runs at "some point" in time during that whole page life cycle on the server.
In fact, what I am saying, it is REALLY hard to mess this up, since just about any event can add the header - but page load looks to be as good as any event here.
Edit: The page load event
You thus should see/be able to add the event to page master like this:

execute C# event handler and after that js function

I have button:
html:
<asp:Button ID="MyBut" runat="server" OnClick="MyBut_Click" CssClass="MyBut" />
C#:
protected void MyBut_Click(object sender, EventArgs e)
{....}
JS:
$(document).ready(function () {
$(".MyBut").click(function () { alert("!"); });
})
Now js function is executed first, after that C# method is executed .
Can C# method be first?
Not really. The C# method is called in code-behind (you are using ASP.NET), and that gets called only upon page reload when the server executes the back-end code to form the updated page.
What you could do is to have the server-side code (the C# code) generate client-side JavaScript that would then be executed as the page reloads in the user's browser. That code would then be executed, of course, after the server-side C# code. See Inject Javascript from asp.net code behind files for an example.
Another option would be that you use AJAX to call the server-side code (so instead of code-behind). Then you can determine the sequence yourself. For more on AJAX with ASP.NET, see http://www.asp.net/ajax.
So someone clicks a button on a page, the JS fires first and then the C#? This is the only possible sequence of events. The JS on the page that handles the click of the HTML button, fires the event to the web server, and then C# runs on the web server.

How to call javascript function and c# code on asp:button?

When a user clicks a button on ASP.net page, I need to
Save file from asp:fileUpload in a folder on a server - I guess this needs to be done in C#, like in How to correctly use the ASP.NET FileUpload control
Run a javascript function like in How to call javascript function from asp.net button click event
Is there a way to combine C# and Javascript to achieve what I need? If not, how should I do it?
Try using the onClientClick property of the asp:button element.
Ex, on your .aspx file:
<script type="text/javascript">
function myFunction()
{
alert('hi');
}
</script>
...
<asp:button id="Button1"
usesubmitbehavior="true"
text="Open Web site"
onclientclick="myFunction()"
runat="server" onclick="Button1_Click" />
And in your code behind (.aspx.cs)
void Button1_Click (object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
}
}
More info at
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
Note that no JavaScript actually "runs" until the server-side code (C# in this case) has entirely completed and the resulting page is returned to the client. Once that page renders on the client, then JavaScript runs on the client.
So in order to execute your JavaScript code, all you need to do is include it in the page being returned to the client. There are a number of ways to do this, and the options depend on whether you're using WebForms or MVC.
You might use something like RegisterStartupScript in WebForms, for example. Or, you could just have the JavaScript code exist in a PlaceHolder control with Visible=false and only make the control visible in the response which intends the JavaScript code to run. (Roughly the same method is also easily usable in MVC by just wrapping the JavaScript code in a server-side condition to determine whether to render it or not.)
The main thing to remember is that you're not "running the JavaScript code from C#" or anything like that. There's a hard separation between server-side and client-side code. The server-side code ultimately builds the page that it sends back to the client, and that page can include JavaScript code to run on that client.

Dynamic data for JQuery in ASP.NET pages

Problem
I have some pages that need dynamic data from website to generate output to users.
A simple solution is an aspx(php, ...) page to generate data and create another html page serving as GUI retrieving data from first page and showing it to users. in this method I can call my GUI page for example form1.aspx and my data page form1.json.aspx.
although I personally like this method, it is not suitable when creating components for it.
Another method that currently I'm using is using same GUI page call itself with a querystring to retrieve data. this page should check for that query string and if it exists, only generate data and remove everything else from page. As an example for this method if I call my page form1.aspx, to retrieve data, I need to call it like form1.aspx?JSON
Here is an example of what I'm doing:
protected void Page_Load(object sender, EventArgs e) {
if (Request.QueryString.ToString().IndexOf("JSON") == 0){
this.Controls.Clear();
Response.Clear();
// send pure data to client
} else {
// render page as GUI
}
}
However this method becomes too messy if I add master page and/or inherit my page from some template page. Master pages can only removed in Page_PreInit and that adds another extra method.
Security controls cause another problem, if user leaves page open for long time until session expires any attempt to retrieve data will fail cause security module will redirect the request to login page.
Next problem is I cannot consolidate my component in package because it needs modification in page (removing master page, clearing page components ...).
What I'm looking for:
1- I'm looking for a solution that I can call my page and get pure data (JSON or XML format) and doing so run a server side method that generates data, so I don't have to worry about what another designer puts in their master page or template.
2- I think it is possible to use axd extension to do this but I don't have a clue about it and couldn't find a helping document either.
3- Is there any better way of doing this. any suggestion or solution to improve this much appreciated.
Page methods. Check this article: http://weblogs.asp.net/craigshoemaker/archive/2008/09/29/using-jquery-to-call-asp-net-ajax-page-methods.aspx or http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
WCF JSON service: http://www.codeproject.com/Articles/327420/WCF-REST-Service-with-JSON
Other ways of doing is using an HTTP Handler. Implement IHttpHandler interface and register your implementation in your Web.config file. Later call it using jQuery ($.get / $.post):
http://msdn.microsoft.com/en-us/library/46c5ddfy.aspx
EDIT
As OP pointed out, in order to access session state in a page method you should use WebMethodAttribute this way:
[WebMethod(EnableSession = true)]
I think you can use webservice instead of aspx page to return a JSON or XML string and then the caller page (any aspx page) will response after process is success.
So with this webservice, any third party page will have access to your server side method.
To create a webservice pls Check this link: Create and use Asp.net web service basic
Regards

How to clear Session when navigating away from one page

I googled this about 1/2 a hour no hit's. Scenario is that, dynamic scripts are saved in string builder whose "string" representation is stored in session. It just happens that when user navigates away from one page to another the script[from session] gets registered using "RegisterStartupScript". The script is registered in PreRender event of the Page. So i would like to clear this script in session while the page navigates away btw rule out a option to create another session variable and clear previous one. It's a overhead :(
Why are you storing this in Session, do you need to maintain this script in between GET requests?
If only postbacks are relevant you could store it in viewstate as this is maintained only when doing a postback.
If you want this string to be available on GET requests too you might want to introduce a different variable which has an identifier identifying the page for which the script is generated. If the requested page doesn't match the control variable you will have to generate a new script.
How is the user navigating away from the page? Can't you use an ASP.NET button instead of a hyperlink, and then do a Redirect in code once you have cleared your session variable?
protected void btnDoSomething_Click(object sender, EventArgs e)
{
Session["Value"] = String.Empty;
Response.Redirect(strURL, false);
}
OR You could add a variable in the query string and check it in the Page_Load event of the target page:
Webform1.aspx?reset=true
Since I cant comment yet, use onUnload().
It fires on full postbacks too. Ajax postbacks dont fire!
What you need to do, is guaranty inside the onUload function that you only clear the session when you want. Like setting a variable isPostBack to true before the postbacks so onUnload sees the variable and doenst send a request to clear the session.
You may use the JavaScript onUnload() and call an AJAX service, that will clear the server side session.

Categories