What is the best way to use JavaScript in an ASP.NET Controller to navigate to a different webpage?

I'm currently developing a website using Angular 1 with an ASP.NET MVC backend. I'm trying to create a link that will gather certain parameters using JavaScript, retrieve the correct URL from a controller, and then redirect the user to a different website. Unfortunately, none of my attempts seem to be successful.

Here is the relevant HTML code:

<a href="#" target="_blank" id="Link">Some text</a>

This is the JavaScript function I have implemented:

$("#Link").on('click', function (event) {
        event.preventDefault();
        window.location = "/Data/SendToOtherSite?Name=" + $("#nameTextBox").val() + "&Email=" + $("#emailTextBox").val();
    });

And here is the method in my controller:

public ActionResult SendToOtherSite(string Name, string Email)
        {
            string url = System.Web.Configuration.WebConfigurationManager.AppSettings["OtherSiteUrl"] 
                + "/Data/DataFromOldSite?name=" + Name + "&email=" + Email;
            return Redirect(url);
        }

Even though I have set a breakpoint on the SendToOtherSite() method, it is never triggered, and the user is not redirected to the new website. What am I missing or doing wrong?

Answer №1

Here is a suggestion to improve your code:

$("#Link").click(function (event) {
    event.preventDefault();
    window.location.href = '@Url.Action("SendToOtherSite", "Data")?name=' + $("#nameTextBox").val() + '&email=' + $("#emailTextBox").val();
});

To ensure the action method parameters are correctly parsed by the MVC standard binding process, it is important to format them properly. It is recommended to utilize the @Url.Action() method to construct the accurate route.

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

Navigating through Leaflet to reference a .json file

Looking to integrate a .json vector layer into a Leaflet.js map, which can be seen on the GitHub page here, with the source code available here. Here's a condensed version of the file for reference (full version visible on the linked GitHub page). & ...

Navigating to two separate webpages concurrently in separate frames

I am working on creating a website with frames, where I want to set up a link that opens different pages in two separate frames. Essentially, when you click the link, one page (such as the home page in a .html file) will open in frame 1 on the left side, ...

Tips for displaying previous values when discarding changes to a record in a material-ui table

How can I prevent changes from reflecting in a material-ui table when clicking on the X icon while editing a row? Is there a way to only save the edited record on the check (_) icon instead? Any suggestions or solutions would be greatly appreciated as I am ...

Problem arises in IISExpress with duplicate key error when specifying virtual path while adding a webServer handler

I am facing an issue with my MVC5 app in VS2013. I am trying to add handlers to the root Web.config file. Everything works fine when there is no virtual directory specified. However, when I do specify a virtual directory, IIS Express fails. Here is how yo ...

Halt the script if the file has not been successfully loaded

Looking for a way to halt the script until $.get() has completed executing in this code snippet. $.get("assets/data/html/navigation.html", function(response) { $('body').append(response); }); $('body').append('<div class="m ...

Angular 8 utilizes JavaScript for its programming language

Looking for a solution in JavaScript - check out: codepen.io/skovtun/pen/VwLvXPB Struggling to find an equivalent for Angular 8+. I want the center block to maintain a fixed width of 1200px, and automatically compress when the left, right, or both sideb ...

Modifying tags or categories of a post using a sidebar plugin in WordPress Gutenberg

I am currently working on integrating the functionality to add or delete a post's tag or category using a WordPress Gutenberg sidebar plugin built with React and JavaScript. Despite the lack of detailed resources on how to implement this particular us ...

Launch a new window for a div when a button is clicked

Hey everyone, I need some help with opening a div in a new window. Currently, I am using window.open and it is working fine. Here is the code snippet: <div id="pass">pass this to the new window</div> <a href="#" onclick="openWin()">clic ...

Understanding how to accurately pair specific data points with their corresponding time intervals on a chart

I'm currently working with apexcharts and facing an issue with timestamps. I have data for sender and receiver, each having their own timestamps. The x-axis of the graph is based on these timestamps, but I am struggling to map the timestamp with its r ...

Callback for deletion in the Mean Stack

I have successfully implemented the delete functionality in my Mean stack application; however, I am facing an issue with updating the view after deleting an item from the JSON. On the server side of my express logic: .delete(function(req, res) { Ser ...

Steps for correctly invoking a function based on input value conditions

Lately, I've been developing a new website geared towards serving as a platform for various travel agencies to showcase their tour packages. The homepage features a functional filter section that enables users to search for offers based on different ...

Creating and experimenting with AngularJS applications (and applications overall)

I am currently working on developing an app, following the trend of using a REST API for the back-end and Angular (previously Backbone and jQuery) for the front-end. Initially, stubbing the REST API for testing purposes is straightforward; however, as deve ...

The client side script "/socket.io/socket.io.js" was not located, therefore the Express-generator project was used instead

I have been working on integrating the "chat-example" from Socket.IO's official website into an Express-generator generated project while keeping the structure of the project intact. I have made minimal changes to the code to fit it into the existing ...

Exploring the World of 2D Array Animation

I'm in the process of creating a Pacman ghost using visual 2D arrays. I would like the ghost to move similar to this: https://i.sstatic.net/KPmUt.gif I am considering implementing CSS transitions for the movement, but I'm unsure about how to do ...

What is the process of using a For loop to output a string in reverse order?

I'm attempting to reverse the string "hello" using a For loop, aiming for the output of "olleh". However, I'm facing an issue where the last character in the string is not being removed after being added to the array. Consequently, only the last ...

The functionality of AngularJs routing does not seem to be operating as anticipated

Please check out my demo example on Plunker. I have been experimenting with integrating the AdminLTE template with AngularJs Routing. I have defined the routing rules in my app.js file as follows: app.config(function ($routeProvider, $locationProvider) { ...

Choose a text input form field simultaneously?

Is it possible to create a select field that also acts as an input form simultaneously? I need the options in this hybrid field to range from 0.01 to 10.00, while ensuring it always displays 2 decimal places. Curious how I can achieve this functionality ...

Combining strings within a string after a specific word with nested Concatenation

In a given string variable "str," I am looking to concatenate another string between "InsertAfterMe" and "InsertBeforeMe". str="This is a string InsertAfterMe InsertBeforeMe" s1="sometext" s2="soMoreText" aList=[1,2,3,4,5] The concatenated string shoul ...

Apple Automation: Extract a targeted string from text and transfer it to a different spot within the page

Apologies for my lack of expertise in this area, but I hope to convey my question clearly. I am working on a form where I need to input text in order to copy specific items and paste them elsewhere on the same webpage. For example, if the input text is " ...

What is the best way to set the width of a w2grid to 100%

Has anyone tried using w2grid before? I'm having trouble figuring out how to make it fill its container 100%. Here's the HTML snippet: <div id="a" style="width:100%"> <!-- top left container--> <div>This ...