Executing a C# method from within a .js file using a Javascript function in a .cs file

I've made some updates based on the responses provided. My main area of confusion lies in the 'data' parameter and how to handle it in the JavaScript call.

C# method

[HttpPost]
        public string GetPreviewURL(string activityID)
        {
            try
            {
                var requestContext = ContextHandler.GetRequestContext(Request);

                object[] arguments = new object[] { requestContext };
                var sew= SumtContainer.Resolve<ICLWOrker>(typeof(ICLWOrker).FullName, arguments);

                return sew.GetPreviewUrl(activityID);
            }
            catch (Exception e)
        }

When making this JS call, I believe the parameter after "POST" should be 'data', but I'm unsure about extracting the URL from the JSON data.

apiAccessClient = new apiClient();
        var apiUrl = STRING_SITE_PREFIX + '/service/webapi/GetPreviewURL/?activityID=' + actId;
        //How do I define 'data' here?
        apiAccessClient.send(STRING_USERMODE, apiUrl, "POST", data, onPreviewSuccess, onError, 0, null, false, false, true); 
        return;

The setup for apiAccessClient is currently in a separate JavaScript file where the Ajax call is configured

$.ajax({
    type: this.requestType,
    url: this.apiUrl,
    contentType: "application/json; charset=utf-8",
    context: this,
    async: isAsync,
    data: JSON.stringify(flattenModel(this.parameters)),
    statusCode: {
        401: function () { _UTL_NavigateToTimeOutPage(); }
    },
    beforeSend: function (request) {
        // Set headers here
    },
    success: function (data, statusCode, jqXHR) {
        // Handle success response
    },
    error: function (jqXHR, textStatus, errorThrown) {
        // Handle error response
    }
});

Could someone provide guidance on how to open the URL received in a new window?

Appreciate your assistance!

Answer №1

It's important to note that JavaScript runs on the client side, while C# runs on the server side. If you want to call a method, you'll need to use AJAX. Here is an example of what the client side code could look like:

function launchURL_Test() {
var ID="your id";


 $.ajax({
    type: "POST",
    url: "yourcontroller/GetUrl",
    contentType: "application/json;charset=utf-8",
    data: "{'id':'" + ID + "'}",
    dataType: "json",
    success: function (data) {

      // do something with the result...

    },
    error: function (result) {
        console.log('error')

    }
});
}

If you are not using a controller and instead using code-behind, your method should be structured like this:

[WebMethod]
public static string GetUrl(string id)
{
   //some code
   return url;
}

In a standard MVC Controller, your method would be formatted like this:

[HttpPost]
public ActionResult GetUrl(string id)
{
    //your code
    return url;
}

Finally, to open a new window with the URL from the method, update your ajax success function like so:

success: function (data) {

  window.open(data);

},

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

What is the process for integrating a tensorflow.js model into a React-based web application?

I've been working on a React web application in Typescript that involves loading a tensorflow.js model and then applying it each time the component updates. While I successfully implemented this in a small demo app without React, I am facing some chal ...

utilizing eval() in order to retrieve a pointer to an include

I am currently developing a form widget where the form schema is fetched from an API and generated dynamically. The library I am using for this purpose (vue-form-generator) comes with built-in validators that are directly referenced within the library itse ...

Adding more rows to the array and then inserting them into the database

Seeking some clarity and appreciation in advance for any assistance! I've organized an array of information within a table that I can edit and then sync with my database once updated. <input type='button' value='add row' id=&a ...

Group a set of x elements together within a div, and then group a distinct number of elements together after every x-grouping

Is there a way to achieve a looping structure like this? For instance: Group every 2 divs into a new div, then (after every 2nd grouping) group every 3 divs together <div id="container"> <div></div> <div></div> ... </div& ...

What could be the reason for my code generating the error [$http:badreq]?

I'm currently attempting to retrieve JSON data from a certain URL and am having trouble getting it to work. Despite going through the Angular documentation and other resources, I still can't pinpoint the issue due to my limited experience with An ...

When a specific option is selected in a `select` element with the `multiple` attribute, activate the change event

Is it possible to trigger a change event on individual options within a standard select element using jQuery or another method? I want the change event to be triggered on the option elements themselves rather than on the select element, as multiple options ...

What causes the AJAX JSON script to output an additional 0?

Within my WordPress website, there is an AJAX function that reaches out to a PHP function in order to retrieve a specific value from a transient record stored in the Database. Whenever I trigger this function with jQuery, I successfully receive the result ...

In my Node.js application using Express and Passport, I encountered an issue where res.locals.users is functioning properly but the data it

I'm currently working on an application using NodeJS, Express, and Passport. However, I've encountered an issue when trying to display user data in the views. While I am able to retrieve the ObjectID of the user from res.locals.user, accessing s ...

Leveraging a single jquery ajax request to handle various loops

I've been pondering if it's possible to have multiple loops, each with its own Ajax call. My goal is to create a golf scorecard where I can retrieve data for the scorecard and players in a single JSON/Ajax call... This is how I retrieve the scor ...

Does the default input default to text format?

I have a somewhat peculiar question. I'm currently experimenting with Javascript for a plugin and came across an interesting scenario. Let's say I have an input element that is structured like this: <input type='cc' id='cc&apo ...

Using Grails to link a select box to an object's ID along with a remote field

Encountered a quirky issue that is becoming more and more aggravating Situation: I have a collection of domain objects, each one equipped with a g:select component linked to it which is displayed by a remote field. How can I associate the status variable ...

I want the name of the hospital to be displayed in the dropdown menu with a shortened version of the hospital's name appearing

Check out my code snippet: here import Autocomplete from "@mui/material/Autocomplete"; import TextField from "@mui/material/TextField"; import React, { useState } from "react"; const hospitalList = { docs: [ { _id: ...

What could be the reason for document.body.style.backgroundColor not working properly?

I am currently experimenting with a logic that triggers the screen to turn black upon pressing the print screen key. Despite changing the background color, it is not functioning as expected. The console has detected a change in value. What could be going ...

Instructions for making dropdown menus that dynamically reduce their options as you make selections:

I have an HTML form structured like this: Within the dropdowns, there is a uniform list of choices: Option 1, Option 2, Option 3. Users must select a value for each key, which currently functions correctly: Yet, I am seeking to enhance this functionality ...

Error encountered with modalpopupextender validation functionality

Is there a way to prevent the submit button on the ModalPopUpExtender from causing a postback when validation errors occur? I am looking for a solution to implement validation on the ModalPopUpExtender in order to avoid postback when errors are present an ...

Using AngularJS, learn how to populate array objects within a JSON object

I'm trying to load array objects from a multi-select control, then populate a model object called "name" with its name and age values. After that, I want to load an array from a select element into the model object. However, the ng-model directive on ...

Is there a way to update page content without having to refresh the entire page?

My goal is to refresh specific content on a page without having to reload the entire page using JavaScript or jQuery. Since my project is built in PHP and JavaScript, I encountered this issue. Note : I want the page content to refresh when a user performs ...

The AJAX Contact Form seems to be malfunctioning

I've encountered a persistent issue with my AJAX Contact Form, and all attempts to resolve it have been unsuccessful. The error message from the jQuery section if(html==0) keeps appearing. If anyone can offer assistance in identifying and fixing this ...

Passing a pair of variables through an onclick event back to the original page

Is there a way for me to click on a list element and have it display 2 variables on the same page depending on which one I click? Currently, I have two variables defined in the HTML code (although this could be changed as I am hardcoding them into the HTM ...

Maximizing Efficiency in Databases and Enhancing POST Request Performance

As I work on my latest application, the focus is on enabling real-time user interaction through multiple AJAX POST/GET requests to the server. This dynamic exchange results in database operations for both reading and writing, with the server responding bac ...