Why onclick event triggered when page is reloaded - c#

So, I have a button in my .cshtml file:
<div>
<button id='btn-next' name='next' type='button' onclick='function f() {
#{
Console.WriteLine("BeforeCalling");
myClass test = new myClass();
test.TestMethod("123");
Console.WriteLine("AfterCalling");
}
}' class='btn btn-block btn-secondary'>justAButton</button>
</div>
Why does it 'clicked' (I see the console output in terminal) when my page reloads? But, if I click the button manually - nothing happens. It works only on page reload.

onclick is a client-side JavaScript event handler. So whatever you want to do there happens in the user’s browser.
However, Razor syntax is executed by the server before anything is sent to the client. Razor is what is being executed in order to generate the HTML that the server sends to the user which then gets interpreted by the browser. But at the time the browser renders the HTML (and registers any JavaScript event handlers), the server is already done.
So what this basically means is that you cannot have server-side code run as part of client-side events. The Razor code you have there runs when the HTML gets generated and none of that logic is sent to the client (you can check that by looking at the HTML source in your browser).
If you want the server to do something when a client-side event occurs, you will need to have the client (=the browser) communicate back to the server, e.g. using AJAX requests. Alternatively, you could look into Blazor if you want to approach this without having to deal with JavaScript.

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.

Javascript confirm box in C# code behind

I am trying to show a javascript confirm box in the middle of some server side code and after getting user confirmation continue processing but confirm box does not show up. I even wrote some sample code but no success.
after some server processing I need to ask user a question and after user confirmation continue some other server code. it seems to be very simple. even alert box work. How can I solve it?
please note that I can not call javascript confirmbox straight from buttonclick I need to do some serverside code and if that was ok then I want to show a confirmbox for continuation.
here is the code
<asp:Button ID="btn_deletefromDB" runat="server" OnClick="btn_deletefromDB_Click" Text="Delete from Datatbase);" />
protected void btn_deletefromDB_Click(object sender, EventArgs e)
{
//Delete service from Database
// some server side processing code
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "return confirm('Do you want to delete it from runtime too? Click OK to proceed.');", true);
Label1.Text = "delete from runtime confirmed";
// continue and delete from runtime
//bla bla bla
}
Instead of triggering this in the code-behind, you should add it to the Button1 OnClientClick event like so:
<asp:Button ID="Button1" runat="server" OnClientClick="return confirm('Do you want to delete it? Click OK to proceed.');" OnClick="Button1_Click" />
Web applications do not work like this. You cannot ask for user input in the middle of page's server-side life-cycle. This question has to be asked client-side and user's response has to come to the server as part of the page's submitted data.
All ScriptManager.RegisterStartupScript does is contributes to the final html content that will be sent to the client when the page completes request processing. Keep in mind that by the time this html content arrives to client computer the user may have closed the browser and gone home.
Use AJAX to submit query to server and make the server code so that it does it’s processing in two parts. I don’t have any working examples of this but this is how it would work in general. For posting data to server you can use native AJAX objects in JS or any other library as others suggested and for processing data on the server side you can use generic handlers (ashx) instead of standard web pages.
Send request to the server.
Catch the first part of the processing via JS on the client page.
Show JS window
Submit the other part to server
You’ll have to send results of the first part of processing back to the client because server will not be able to connect second request with the first one by default.

Event when form submittion ends

I have this:
<form id="import_form" method="post" enctype="multipart/form-data" action="/Blah/Blah">
<input type="file" id="fileUpload" name="fileUpload"/>
<input type="submit" name="submit" value="Import"/>
</form>
$('#import_form').submit(function () {
...
});
Here is the c# method:
[AcceptVerbs(HttpVerbs.Post)]
public string Blah(HttpPostedFileBase fileUpload, FormCollection form)
{ ... }
I want when Blah finishes executing a javacript code to start executing. How to do this?
The submit event is called before it.
This depends on how the form is being submitted.
If you're submitting the form via AJAX then you can execute some JavaScript in the handler for the response. However, given that there's a submit button, I'm assuming for the moment that you're not doing this via AJAX and are instead posting the whole page to the server and rendering a response.
In this case, to execute some JavaScript after the form post, you're going to need to render that JavaScript in the response from the server as part of the next page. When the server constructs the view, include the JavaScript you want to execute in that view.
Keep in mind the request/response nature of the web. When something on the server executes, the client is unaware of it and disconnected from it. The end result of any server-side processing should be an HTTP response to the client. In the event of submitting a form or clicking a link or anything which results in a page reload, that response is in the form of a new page (view). So anything that you want to do on the client after the server-side processing needs to happen as part of that response.
Edit: I just noticed that Blah is returning a string. Is this even working for you? How does the form submit result in a new view? Or am I unaware of a feature in ASP.NET MVC?
This is what I did in the end.
My form returns the exact same view with whom it was called.
I add a ViewData in the Blah method.
In the view, in the $(function()) event I check if ViewData has a value, I execute the javascript code.

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.

Run javascript function after Server-Side validation is complete

Ok, I've got a lightbox with a small form (2 fields) in it, inside an UpdatePanel, and I want to close this lightbox (must be done via javascript) when the 'Save' button is pressed.
However, there is a need to have a server-side CustomValidator on the page, and I only want to close the lightbox if this returns as valid.
Does anyone know a way to trigger javascript (or jQuery) code from a server-side validator?
You can add a little snippet of code using the ScriptManager to execute after the response comes back to the UpdatePanel.
if (Page.IsValid){
ScriptManager.RegisterStartupScript(
customValidator1,
typeof(MyPageClass),
"closeBox",
"myLightBoxVariableOnThePage.close()",
true);
}
When that server side validator runs, it will send a whole new page to the browser. Anything that was shown in the browser before was destroyed, including any state kept in your javascript. If new page bears a strong resemblance to the old page, you should consider this a happy coincidence.
Therefore, the thing to do here is rather than executing a javascript function, have your CustomValidator make the correct changes to the page on success so that it's rendered to the browser correctly in the first place.

Categories