execute C# event handler and after that js function - c#

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.

Related

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.

how to call a javascript function from codebehind in asp.net

protected void addSchoolButtonClick(object sender, ImageClickEventArgs e)
{
Page.ClientScript.RegisterStartupScript(GetType(), "MyKey1", "SchoolSearchPopUp();", true);
/*Some code*/
}
I am developing a website in asp.net.At a Hyperlink onclick event i want to call a javascript function"SchoolSearchPopUp()".this function is for creating a new popup window and it is working correctly.But my problem is ,a javascript function is calling or pop window opens only after executing the rest of the code in that function and that code need's some data that occurs as a result of popup.How can i create the popup before executing the rest of code in that function.
Change your postback trigger to something within the popup.
I don't think javascript can be called from code behind. C# is running from the server and java is all client side. There's a good explanation to a similar question here: http://forums.asp.net/t/1117189.aspx
If you need to execute a javascript function, you could try changing the hyperlink to a button and making use of the OnClientClick property. This executes script client side rather than calling a method on the server.
<asp:button id="Button1"
text="Click Here"
onclientclick="SchoolSearchPopUp()"
runat="server" />
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
You will need to write JavaScript on the page to handle the click of the button first and then call to the page method on the server.
Add an OnClientClick attribute to your button element and run your JavaScript method from there:
<asp:Button ID="TestButton" OnClientClick="SchoolSearchPopup()" Text="Click Me" OnClick="addSchoolButtonClick" runat="server"/>
<script type="text/javascript">
function SchoolSearchPopup()
{
alert("Popup");
}
</script>
If you want to execute some javascript before your postback you will need to register your hyperlink's click event to a js method, then submit your post to the server after performing whatever client side logic you are looking to run. (not the other way around, using RegisterStartupScript)
Example:
$("#myHyperLink").click(function() {
// do page logic, in your case show a modal window
$("#myModalDivContainer").show();
// submit your post to the server... replace targetClientID with ID of server control you're posting to
__doPostBack('targetClientID', '');
// NOTE: If you want to perform an AJAX request instead simply use some jQuery here instead. it's up to you how to handle the request from this point :)
});
Hope this helps!

How to execute jquery script before page load?

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.

Sys.WebForms.PageRequestManager pageLoaded event caching function?

I've got a master page that contains this code at the bottom of the page:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(parseData);
</script>
</form>
the parseData() function I'm creating inside the main page and I'm adding functions to it based on each page load. parseData IS called after every AJAX refresh, but it appears to only call the contents of the function from BEFORE the request. If I hit F5 to refresh the page again, it will properly call all of the newly added content in the parseData function.
Does this function cache that data? How can I make sure it calls the newly created contents of the parseData function?
According to the research I did, this is a problem with MS AJAX UpdatePanels and you are really better off not using them. I revised my JavaScript to pull data from hidden form fields instead so the JavaScript functions never changed and was able to get this working.

Registering asp:button click event handler

I have multiple asp:button that I created dynamically with jQuery.
For each of them, I have OnClick="ibtn_Click" .
But on the code behind, I have to manually register each one of them on Page_Load..like.. button.Click += new EventHandler(this.ibtn_Click); .
Is there a way I can register this handler automatically? Or is it possible to register it with ajax jquery?
Thanks!
You can't add ASP.NET web controls in the client's browser. ASP.NET transforms those <asp:button> tags into regular HTML, something like this:
<input type="submit" name="Button1" value="Ok" id="Button1" />
When a user clicks one of these submit controls, the browser sends a POST request, which includes the button's name as part of the posted data (which you can access via the Form collection in ASP.NET):
if (this.IsPostBack && Request.Form["Button1"] != null) {
// do something if the user clicked Button1
}
ASP.NET automatically binds server control clicks to the methods specified in the OnClick attribute. It calls the method after Page.Load completes (for the gory details, see "ASP.NET Page Life Cycle Overview").
If you're adding the buttons on the client, you can do all this yourself. For example you could "bind" the dynamically generated button in Page_PreRender:
protected void Page_PreRender(object sender, EventArgs e) {
if (this.IsPostBack && Request.Form["Button1"] != null) {
// Call another method on the page
}
}
Finally, in this day and age, if it's appropriate, you should definitely consider just calling page methods via jQuery's ajax. See this excellent Encosia article for an introduction to that technique.
Is your purpose of generating dynamic asp.net buttons to call code behind?
you can generate html "Submit" button (type=submit) and call webMethods from javascript.
The webmethods are than redirected to you c# code behind

Categories