Search code examples
asp.net-mvcasp.net-mvc-5

Open a link in new tab from controller in ASP.NET MVC


I want to display a hyperlink in browser and when I click on the hyperlink the request goes to my controller and open the URL in new tab of the browser.

Any idea how can I achieve this?

@*This is index.cshtml*@
@{
    ViewBag.Title = "Index";
}

<h2>Click on the link below</h2>
@Html.ActionLink("GOOGLE", "NewWindow", "Home")
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult NewWindow()
        {
            return Content("<script>window.open('https://www.google.com/','_blank')</script>");
        }
    }
}

This code is showing error. Please help


Solution

  • Use target="_blank" to open a link in a new window.

    @Html.ActionLink("GOOGLE", "RedirectToGoogle", "Home", null, new { target = "_blank" })
    

    In the controller, return a redirection to the required URL:

    public ActionResult RedirectToGoogle()
    {
        return Redirect("https://www.google.com/");
    }