[RESOLVED]execute razor function inside Javasscript

Hi,

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)
        {
            @Referential.InstantlyEmailNotification(HttpContext.Current.User.Identity.Name);
        }
    }
</script>

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){
        if(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!");
                 });
        }
    });
</script>

<!-- 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 

[HttpPost]
public void SendEmailAction()
{
     // Send your email here
}

Leave a Reply