0

I noticed that when a link on the page has JS onclick function and also a MVC action method, the JS function fires before the action.

  1. Wondering is this always the case?

  2. Why/how browsers deside to run JS and the the backend method?

  3. Can I run backend method first, but still want to fire the JS function?

Regards

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
Xavier
  • 389
  • 7
  • 20

3 Answers3

3

Wondering is this always the case?

Why/how browsers deside to run JS and the the backend method?

Client-side JavaScript runs on the client, inside a page. Server-side .NET code runs on the server and generates an HTML document (or other resource).

To run server side code, the browser has to make an HTTP request.

The easiest way to make an HTTP request is to leave the current page and load a new one from the server (by following a link or submitting a form).

Since client-side JavaScript runs in a page, it can't run after the browser has left the page it runs in.

Can I run backend method first, but still want to fire the JS function?

You can make an HTTP request from JavaScript (before doing other JS actions) instead of leaving the current page. This is usually done with the XMLHttpRequest object and is known as Ajax.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Why/how browsers deside to run JS and the the backend method?

  1. server side code will need a request to return the response. HTTP works on Request and Response architecture. basically client make requests in order to get the response (i.e results or desired data)

wheenever you do postback or return true to the server, it will execute server side methods.

<a href='#' onclick="return SomeFunction();">ClickHereToSee</a> 

here return value which is returned by the function, if you return the true value it will go to the server method, if you returned the false it will prevent the default action.

Can I run backend method first, but still want to fire the JS function?

You can. use Ajax. basically Ajax requests are XMLHTTPRequest. which used to update the paritial portions.

Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83
1
Can I run backend method first, but still want to fire the JS function?

First two answers are already well answered. For third one you can try Jquery Ajax-

function SomeFunction(){     

$.ajax({
                    type: 'POST',
                    url: "@Url.Content("Controller/ActionResult")",    
                    data : {                          
                              *yourparameter:value*   //data
                           },           
                    dataType: 'json',
                    success:function(result)
                    {
                      //javascript stuff                     
                    }
           });
}

<a href='#' onclick="return SomeFunction();">ClickHereToSee</a> 
ssilas777
  • 9,672
  • 4
  • 45
  • 68