1

Summary

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?

Implementation

MyService.js

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'
 });
 }
}

MyCode.ascx

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
$('.myService-start').click(function(){
 api.start(someId)
 .done(function(){
 console.log('start completed');
 })
 .fail(function(){
 console.log('start failed');
 });
});
// Call Stop
$('.myService-stop').click(function(){
 api.stop()
 .done(function(){
 console.log('stop completed');
 })
 .fail(function(){
 console.log('stop failed');
 });;
});
<span class"myService-start">Start</span>
<span class"myService-stop">Stop</span>

Question

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

asked Mar 9, 2020 at 12:05

1 Answer 1

0

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

answered Mar 9, 2020 at 14:31
1
  • 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. Commented Mar 9, 2020 at 15:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.