[RESOLVED]execute razor function inside Javasscript


I would like to execute javascript inside javascrit 

<a href="#" onclick="InstantlyEmailNotification(true);">Notification instantanée par email </a>

If I click the link, I want to execute the function

<script type="text/javascript">
    function InstantlyEmailNotification(action) {
        if(action == true)

I would like to excecute the function and stay on the view ( no conntroller action).

My javascript function is always executed at page load.

Best regards

You can’t do this as your razor code is ran on the server while the static html is being created.  Once sent to the browser it is just simple html and all interaction has to be done via javascript.

Google "call mvc action from javascript" and you’ll find code samples of how you can all actions on controllers, and the action will do the work you need to do.

You’ll need to make an AJAX call to the particular method that you want to access within your Controller. This can be done quite easily using a library like jQuery :

<!-- Example jQuery reference here -->
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<!-- Your script -->
<script type='text/javascript'>
    function InstantlyEmailNotification(send){
                 // Make an AJAX call indicating your image was clicked
                 $.post('@Url.Action("SendEmailAction","YourController")', function(){
                      // When it's complete, alert the user
                      alert("Email Sent!");

<!-- Your Element -->
<a href="#" onclick="InstantlyEmailNotification(true);">Notification instantanée par email </a>

When clicked, this would make a POST request to the following Controller Action and 

public void SendEmailAction()
     // Send your email here

Leave a Reply