Thursday, August 25, 2016

Using Ajax to call static method from Asp.net page


I've been working a lot with .NET framework lately and wanted to share some useful knowledge with others human beings (but if you are a robot, you can also use this post for your tasks =) ).
If we want to call a static method from a cshtml file, the best way to do it is by using AJAX. In the project I am working on, I needed to perform some back-end task at some specific moment when user requests it. The back-end function is supposed to return a URL (string) and then use that new URL to update some of my links in the front-end.
We can directly call a static method from cshtml by just calling it, like this:

@MyClass.methodName("abc")

However, with ASP.net, RAZOR code is executed when the page is loaded, so the only way to "control" when to perform this action is by using AJAX.

This is my code using AJAX:

<script>  
        function vaxGUID() {        
        $.ajax({
            type: 'POST',
            url: "/ControllerName/method",
            data: '{"Name":"anything"}',
            contentType: 'application/json; charset=utf-8',
            dataType: 'html',
            success: function (data) {
                $('a.varURL').attr('href', data);                                
                alert("Good response - " + data);
            },
            error: function (data, success, error) {
                alert("Error : " + error);
            }
        });
        return false;
    }
</script>

As we can see in the method, we are making the call with: url: "/ControllerName/method", this means that is we put that URL in our browser (with any parameter if needed) , we should get a response. That is a good way to test it first. "Data" is returned and then we can use it in the way we need it.




No comments:

Post a Comment