M4s0n
M4s0n

Reputation: 613

Universal apps: call c# method from javascript

I am working with universal apps in Visual Studio 2015 since a few days and I have absolutely no clue how to access a c# method in a class since there is no "WebMethod"-Attribute.

    <script type="text/javascript">
    function getWindowsDeviceUUID() {
        //$.ui.popup({
        //    title: "methodcall",
        //    message: "trying to call methode"
        //}
        //    );
        $.ajax({
            type: 'POST',
            url: 'MainPage.xaml.cs/GetDeviceUUID',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (uuid) {
                $.ui.popup({
                    title: "success",
                    message: "called method"
                }
                    );
                return uuid;
            }
        });
    };
</script>

I already tried it with ajax but the "GetDeviceUUID"-method isn't called. However the getWindowsDeviceUUID is.

Some Additional Information: I already have multiple JS & HTML files I have to use in this app. I open the HTML-Sites via a WebView control.

Kind regards

Upvotes: 0

Views: 1233

Answers (2)

Peter Torr
Peter Torr

Reputation: 12019

Assuming your host app is C# (and your HTML is hosted in a WebView) then you can expose C# methods by calling the AddWebAllowedObject method to inject a C# class that includes the method you want to call. Then from script you can invoke the method via window.whatever-name-you-gave-it.some-method().

Upvotes: 2

Erfan Zarger
Erfan Zarger

Reputation: 270

I think you just need to change the logic. Rather than calling the class directly, write a function that has access to the class in your code behind then used the WebMethod for your function to use the class. If the class is not accessible even in the code behind, then the class need to be changed.

Upvotes: 0

Related Questions