简体   繁体   中英

How do I redirect to another web page from an ASP.NET Controller using JavaScript?

I am working on an Angular 1 website with ASP.NET MVC backend. I need a link to gather some parameters using JavaScript, then go to a controller to get the correct URL, then send the user to a different website. However nothing I try is working.

This is the HTML if it matters:

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

This is my JavaScript:

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

And this is the method on 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);
        }

I have a breakpoint on SendToOtherSite() but it is never hit and I do not get taken to the new website. What do I need to do?

Try the following:

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

The action method parameters should be properly formatted to be able correctly parsed by the MVC standard binding process. Therefore, the @Url.Action() should be used to build the correct route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM