Search code examples
asp.net-mvc-5

MVC5: Open URL from Controller


I know how to route a link to a controller, and I know how to open a URL from the view. But I don't know how to combine the two.

I would generally, keep the opening a URL logic inside the view, but I want to set some variables before I redirect, so I am looking for something that can open a URL from the controller. I want to set some session variables before redirecting to the URL.

So this is what I want:

@Html.ActionLink("Click Me!", "HandleClick", "Controller", null, null)

And in m controller:

public ActionResult HandleClick()
{
    // Set Session variables
    // Open a URL
}

How can I do that? Also, is there any other better way to do this?

Note that the URL here is not a route, it is an external host like http://www.google.com


Solution

  • You can use ajax.actionlink and javascript

    @Ajax.ActionLink("Click Me!", "HandleClick", "Controller", new AjaxOptions() { OnSuccess = "mySucess" });
    
        <script> 
            function mySuccess() {
                window.open('http://www.google.com/');
            }
        </scrip