简体   繁体   中英

ASP.NET MVC - Auto-redirect to external site in View

I have a view that redirects to another view with a simple message after submitting a form. Here (in the view with a simple success message) I would like to be able to redirect automatically after 5 seconds to an external website. This works fine:

<meta http-equiv="refresh" content="5;URL=https://external.site">

The problem is that the url I need to redirect to is dynamic and I have it stored in the Model but this is not working (this reload itself or it does nothing, no error in Chrome console):

<meta http-equiv="refresh" content="5;URL=@Model.SuccessfulRedirectUrl">

I also tried some Javascript but this is not working due to an error similar to this in the Chrome console

Refused to execute inline script because it violates the following Content Security Policy directive...

and this is the code:

@section scripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            var redirectUrl = @Model.SuccessfulRedirectUrl;
            window.setTimeout(function(){
                window.location.href = redirectUrl;
            }, 5000);
        });
    </script>
}

This is the controller that take care of the form submit

[HttpPost]
public IActionResult MyController(MyControllerInputModel myControllerInputModel)
{
    try
    {
        if (ModelState.IsValid)
        {
            // Here there are only DB Querys to get data I need ...

            // redirectUrl is from DB
            return RedirectToAction("RedirectController", new RedirectModel(redirectUrl));
        }
        
        return View(new AnotherView()));
    }
    catch (Exception e)
    {
        return BadRequest();
    }
}

The controller of the simple message (RedirectController) just return a new View passing the redirect url specified

Can someone tell me if it is possible to do what I want? As an alternative solution, I can think only to put a button in the page to let the user redirect on click but it's not the same at all

Apparently there was a mistake in the Controllers. I am fairly new to this and I was passing the wrong parameter when using RedirectToAction.

This was the old (and wrong) RedirectToAction:

return RedirectToAction("RedirectController", new RedirectModel(redirectUrl));

This is the modified (and working) RedirectToAction:

return RedirectToAction("RedirectController", new { redirectUrl = user.RedirectUrl });

After this edit, this solution is working correctly:

<meta http-equiv="refresh" content="5;URL=@Model.SuccessfulRedirectUrl">

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