Instead of calling WebApi straight from a Web Forms User Control, I have created JS class which contains functions returning jQuery AJAX requests. The control would instantiate the class and call these functions, which would allow me to separate the code that calls the API from my control.

Is this the best approach? What down-falls could there be later?



Assume my WebApi controller is called MyServiceController. The client-side JS class would be:

class MyService
    //  Example method to call
    start = function(userId) {
        return $.ajax({
            url: '/api/myService/start',
            type: 'POST',
            data: {
                id: userId

    // Another example method
    stop = function() {
        return $.ajax({
            url: '/api/myService/stop',
            type: 'POST'


This will then be consumed from the web forms control as so:

// Instantiate the class
var let api = new MyService();

// Assume document has loaded and add click-handler
var someId = 1;

// Call Start
            console.log('start completed');
            console.log('start failed');

// Call Stop
            console.log('stop completed');
            console.log('stop failed');
<span class"myService-start">Start</span>
<span class"myService-stop">Stop</span>


Am I following a bad pattern? Will this lead to a code-smell later on?

Please let me know if there's a better way to implement this

1 Answer 1


Yes, its good practice.

You presumably will want to use the api in several different places through your app and this will save you code and make things cleaner.

I would go further and put the javascript client in its own project so you can use it across multiple projects, distribute it via npn, add typescript types, change from $.ajax to the native fetch(), upgrade from webforms?!?!!!?!!! etc

  • Thanks @Ewan. I doubt I'll be using it in several places but it leaves the option open. As for upgrading from webforms, we already have an MVC.NET app which makes the WebAPI redundant; but the client doesn't want to upgrade because of migrating users over. It's an insurance web-app so I can see their reluctance. But I digress/rant. Mar 9, 2020 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.