Implementing JSON methods in C# WebService to enable communication with external servers

Is it possible to integrate an asp.net web service written in C# into an HTML5/JavaScript website? The challenge is that the web service and client are located on different domains, requiring a cross-domain request.

Answer №1

Transitioning my asp.net pages to HTML5 and JS for a faster interface has been quite challenging, but I've managed to utilize JSON to connect my webservice to JS efficiently. The data size reduced significantly from 2Kb to just 128 bytes, making it more mobile-friendly.

Setting up on the server side

mywebservice.asmx

The web service will be hosted on Site.com.

The address format: "Site.com/MYWS.asmx/JSONMethod"

[WebService(Namespace = "http://...")]
[System.Web.Script.Services.ScriptService]
public class MYWS
{
    [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public string JSONMethod(/*ParType ParName, ParType ParName2,.. etc*/)
        {
                List<object> tempobjects = new List<object>();
                tempobjects.Add(new { ID = id, Val = val /*more params=> ParName= "ParValue", etc..*/ });

                var retVal = new JavaScriptSerializer().Serialize(tempobjects.ToArray());

                Context.Response.ContentType = "application/json";
                var p = "";
                if (Context.Request.Params.AllKeys.Contains("callback") == true)
                    p = Context.Request.Params["callback"].ToString();
        Context.Response.Write(string.Format(CultureInfo.InvariantCulture, "{0}({1})", p, retVal));
        }
}

Implementing on the client side

myJS.js

function MyJSMethod(){
$.ajax({
    url: "Site.com/MYWS.asmx/JSONMethod",
    data:{ParName: "parValue"/*, ParName2... etc*/},
    type:"GET",
    dataType:"jsonp"
    })
    .done(
        function(data){
            //Process the retrieved json data
            //... YOUR CODE HERE ...

            //Call another method if needed
            //window["JSmethod"](data)
        }
    ).fail(function(jqXHR, textStatus, errorThrown ){
    alert(jqXHR);
    alert(textStatus);
    alert(errorThrown);
    });
}

Hopefully this guide is helpful to you as it has been to me. Best of luck with your coding endeavors!

-Poncho

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

combine blank cells in table generated with vuejs

I am attempting to display a table of students where each column represents a subject, and underneath each column are the names of the students who failed in that particular subject. The challenge I am facing is that my data is structured in rows instead o ...

How can `localePath()` be utilized to create a dynamic route with Nuxt i18n?

I currently have this route set up in my i18n.config.js: { pages: { 'rental/_id': { nl: '/verhuur/:id', en: '/rental/:id', de: '/mietbestand/:id', }, } } When attempting to link to this page in my ...

Running a setTimeout function within the context of a jQuery each

My goal is to animate characters one by one, but for some reason the following code isn't functioning as expected: $('.overlay-listing').hover(function(){ var idx = 1; $('.strip-hov span', this).each(function(){ if ...

Clicking on the image in the Swiper Slider will update the URL

Hi there! I am looking for help with changing the image URL when clicked. Currently, I am using swiper for my image gallery. I want to change this URL: to If anyone has a solution or suggestion on how I can achieve this, please let me know! ...

Updating the user interface in react-apollo following a delete mutation

After successfully executing a delete mutation in my React Apollo component, the UI of my app did not update as expected. Here is the code snippet for reference: const deleteRoom = async (roomId, client = apolloClient) => { const user = await getUser ...

Problem with locating elements using Selenium xpath

While using selenium and xpath, I encountered a peculiar issue. On a page, there are 25 <a> tags with nested <img/> tags. I am trying to retrieve all these elements using the findElements() method. Interestingly, upon inspecting the page source ...

Tips on incorporating several class names into Next.js elements

My current challenge involves an unordered list element with the following structure: <ul className={styles["projects-pd-subdetails-list"]}> {detail.subdetails.map((sub) => ( <li className={styles[ ...

The provider of $modalInstance is currently unknown, leading to an error in the MainController

I'm currently facing an issue with my app's modals when trying to call them using $modalInstance. Despite following the advice from other similar questions I found, such as avoiding the use of ng-controller, my modal still isn't functioning ...

What is the best way to create a clickable <li> element from AJAX search results that display dynamic HTML?

Utilizing AJAX technology, I have implemented a live search feature that populates results from a database as the user types in a text field. The results are presented in an unordered list format. My goal is to allow users to click on an item within the li ...

Steps for inserting an item into a div container

I've been attempting to create a website that randomly selects elements from input fields. Since I don't have a set number of inputs, I wanted to include a button that could generate inputs automatically. However, I am encountering an issue where ...

The display of the Ajax Table is not appearing as expected

Currently, I am trying to generate an ajax table from my database. The issue I am facing is that instead of creating the table on the page, it displays a json string. Below, you can find my ajax call and view: <head> <script src="http://ajax.goog ...

Unlocking the full potential of parsing messages using google protobuf-js

Currently, I am developing a front-end application using Angular5+ that utilizes google-protobuf JS and WebSocket for backend communication. Within my .proto files, I have defined 2 objects: a Request object. a Notification object. I have created a han ...

Sending JSON information from a text document to a specific web address

Looking for a solution to post JSON data from a text file to a specific URL, I found myself in unknown territory. I stumbled upon a method of posting JSON data using HttpUrlConnection. Here is my JSON DATA: { "request": { "header": { "signature": "BHNUMS ...

Retrieving a single object from an array in node.js utilizing elemMatch

My goal is to extract a single object from an array of objects in a data collection using elemMatch. Here is the sample data: [ { "_id": "5ba10e24e1e9f4062801ddeb", "user": { "_id": "5b9b9097650c3414ac96bacc", "firstName": "blah", ...

What steps can be taken to resolve the issue with Angular routing?

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import {HomeComponent} from "./home/home.component"; import {SettingsComponent} from "./settings/settings.component"; ...

The use of fs.writeFileSync is invalid and will not work for this operation

Encountering an issue while working with fs in next.js, receiving the following error message: TypeError: fs.writeFileSync is not a function Here's a snippet from my package.json: resolve: { fallback: { "fs": false }, } ...

What's the point of using defer() in Node.js Q promises when you have the option to simply use this

I had a plan in mind: somePromiseFunc(value1) .then(function(value2, callback) { // insert the next then() into this function: funcWithCallback(callback); }) .then(function(dronesYouAreLookingFor){ // Let's celebrate }) .done(); Unfortun ...

bindings and validation of input values in angularjs

In my scenario, I am dealing with a dynamic regExp and unique masks for each input. For instance, the regExp is defined as [0-9]{9,9} and the corresponding mask is XXX-XX-XX-XX. However, when it comes to Angular's pattern validation, this setup is con ...

Identify specific terms within a webpage using an iframe that is integrated onto the same page

Is there a way to implement word highlighting on a webpage containing an iframe with a search field? The concept involves allowing a user to input search terms within the iframe, which would then send a command to highlight those words on the main page. ...

Troubleshooting problem with ng-repeat in AngularJS - attempting to incorporate a new function into the $

Utilizing AJAX to retrieve data from a JSON file, inserting it into the controller $scope, and then employing it in ng-repeat has been successful. However, issues arise when attempting to incorporate a function into the $scope to execute another task. ...