Using a variable in Ajax URL with Action razor syntax

I have a function that calls a method in the controller through an Action URL. However, I need to use a parameter as the name of the method, but unfortunately, this is not possible in the current implementation.

function changeDropDownList(id, dropNameToChange, actionName, descriptionName) {

    var control = $('#'+dropNameToChange);
    control.prop("disabled", false);

    $.ajax({
        //At this point, I would like to use the value stored in the actionName variable; however, it only accepts a string.
        url: '@Url.Action(actionName, "ThirdPartiesDef")',
        dataType: "JSON",
        data: { id: id },
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            control.empty();
            $.each(result, function (index, item) {
                control.append(
                    $('<option/>', {
                        value: item.Id,
                        text: item[descriptionName]
                    })
                );
            });
        },
        error: function (error) {
            alert("Error: " + error);
        }
    });
}

I am not very familiar with AJAX. If you know of any simpler methods, I would greatly appreciate your suggestions.

Thank you for your assistance!

Answer №1

In order to dynamically generate a URL for your AJAX call, you can utilize the Url.Action server-side Razor function and replace it with the value of your JavaScript variable actionName. This process occurs on the client side.

url: '@Url.Action("#THE-ACTION#", "ThirdPartiesDef")'.replace('#THE-ACTION#', actionName)

When this code is executed, the following HTML markup will be inserted into the browser:

url: '/#THE-ACTION#/ThirdPartiesDef/'.replace('#THE-ACTION#', actionName)

By invoking the changeDropDownList JavaScript function on the client, the placeholder will be replaced with the actual value of the actionName JavaScript variable. As a result, the correct URL required for your AJAX call will be generated.

Additionally, it is advisable to remove the

contentType: "application/json; charset=utf-8"
parameter from your AJAX call since no JSON data is being sent via the data parameter.

Answer №2

To convert a JavaScript object to JSON text and store it as a string, you need to utilize the JSON.stringify() method.

The JSON.stringify() method is specifically designed for this purpose in JavaScript, where it transforms a JavaScript object into JSON format.

If your server expects data in JSON format, remember to set the content type as application/json; charset=utf-8 while making requests.

There seems to be an issue with the usage of

@Url.Action(actionName, "ThirdPartiesDef")'
.

You can rectify this by using the .replace function:

'@Url.Action("myAction", "ThirdPartiesDef")'.replace('myAction', actionName)
.

Note that in Razor, any content within the @ block is automatically HTML encoded for security purposes.

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

Unable to Delete Record Using Jquery and Express in 'DELETE' Request

While working on my api using node/express and jquery, I encountered an issue where my DELETE requests are not functioning as expected. JQUERY: $('.formula-body').on('click', function (e) { if (e.target.className == 'fa-trash- ...

Using jQuery in Rails 3 to display the id of a td element

I am working with a 3x3 table that contains td elements with unique id's (id='a1'...id='c3'). I want to enable the user to click on any of these 9 td elements and receive an alert displaying the id of the clicked td. Below is my C ...

Massive Memory Drain Due to XMLHttp POST Request

Is there a way to prevent XHR POST Memory leak in my web app? I have searched extensively for solutions but have not found any satisfactory answers. My issue is similar to the one described in this blog post that outlines the problem without offering any f ...

How can we ensure that Ajax consistently provides useful and positive outcomes?

Here is my PHP code: function MailList() { $this->Form['email'] = $_POST["email"]; $index = $this->mgr->getMailList($_POST["email"]); } // SQL code function getMailList($email) { $mailArray = Array(); $sql ...

Tips for updating the border color of a button:

Struggling to alter the border color of a button Attempting borderColor attribute proved futile: borderColor: '#FFFFFF' Anticipated result Code snippet: headerBtn: { backgroundColor: 'black', fontSize: '16px', f ...

AngularJS withCredentials Issue causing data not to be transmitted

When using AngularJS, I encountered an issue where the cookie/session was not being shared across domains for my Restful API in a subdomain. To address this problem in Angular, I added the following configuration: app.config(['$httpProvider', fu ...

Encountered an error while running the `npx-create-react-app my-app` command in

When attempting to run 'npx create-react-app my-app', the following error message is displayed: 'npx' is not recognized as the name of a cmdlet, function, script file, or operable program. Double check the spelling and path included to ...

How can I send a value to an Angular element web component by clicking a button with JavaScript?

I want to update the value of an input in an Angular component by clicking on a button that is outside of the Angular Element. How can I achieve this in order to display the updated value in the UI? Sample HTML Code: <second-hello test="First Value"&g ...

What is the process for including a JavaScript file in an HTML document?

Greetings to all and thank you for taking the time! I have a straightforward query for you.. I have designed an html page featuring only a basemap (open street map). Moreover, I possess a javascript file which utilizes your coordinates to calculate a perce ...

Deactivating Timeout Requests in Koa Server

I keep encountering a connection reset error. I strongly believe it's stemming from a lengthy REST request, causing it to timeout. { [Error: socket hang up] code: 'ECONNRESET' } Is there a method to deactivate request timeouts within Koa, ...

Is there a way to convert the text within a div from Spanish to English using angular.js?

I am working with a div element that receives dynamic text content from a web service in Spanish. I need to translate this content into English. I have looked into translation libraries, but they seem more suited for individual words rather than entire dyn ...

Error message in vuejs: JSON parsing error detected due to an unexpected "<" symbol at the beginning

I have been trying to troubleshoot this issue, but I am having trouble understanding how to resolve it. Currently, I am using lottie-web in a project and need to set the animation parameters on an object in order to pass them as a parameter later. This i ...

"Can you tell me the method for obtaining an array within an Angular

Within the realm of PHP, there exist certain elements within an array: $this->data['messages']['ms'][] = 'Line1'; $this->data['messages']['ms'][] = 'Line2'; along with a method that return ...

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

An error has occurred due to a connection timeout with the net.Socket

I have been attempting to send text to my network printer using a tcp connection. function print(buf2){ var printer = new net.Socket(); printer.connect(printer_port, printer_name, function() { console.log('Connected'); printe ...

Choose a collection of elements and encase them within a <div> tag

I am currently working on creating a greasemonkey script for a webpage that has a rather challenging structure. My goal is to show and hide different entries, but the content is formatted like this: <a name="first"/> <h3>First</h3> Some ...

Customize the focus function for an individual element

I am working on a custom component that needs to seamlessly integrate with the native blur and focus functions. My goal is to override these functions in order to achieve the specific functionality I need. Currently, I have managed to override the prototy ...

What methods can I use to create a peer-to-peer communications platform with PHP, MySQL database, and JavaScript?

Currently, I am encountering the challenge of creating a communication channel between two users on a website (such as a gaming site) using only the technologies specified in the title. I recently created an online chess platform with the aim of allowing ...

Upload a JSON file to a server using a JavaScript app

I am in the process of creating a basic JavaScript application that allows users to annotate images stored on their machine and save these annotations as a JSON file. This application is lightweight and straightforward, not requiring an app server. Howeve ...

Avoiding special characters in URLs

Is there a way to properly escape the & (ampersand) in a URL using jQuery? I have attempted the following methods: .replace("/&/g", "&amp;") .replace("/&/g", "%26") .replace("/&/g", "\&") Unfortunately, none of these are y ...