简体   繁体   中英

ASP.NET MVC Javascript Redirect encoding issue

I'm trying to use Razor to inject a URL into a Javascript variable, and then redirect the browser to that URL. I need to do it this way as my application is fully AJAX based and I'm redirecting to a Facebook Authentication page.

The view that performs the client-side redirect looks like this:

@model Site.Core.ViewModels.Auth.FacebookCanvasLoginModel

<script type="text/javascript">
    var redirectUrl = '@(Model.FacebookLoginUrl)';

    window.top.location.href = redirectUrl;
</script>

The value of Model.FacebookLogin URL is generated by the Url.Action() helper in MVC.

the problem is that the location that is actually redirected to is:

http://dev.mydomain.net/Auth/RequestPermission?permissions=read_stream%2Cuser_photos&amp;redirectUrl=http%3A%2F%2Fdev.mydomain.net%2Fnewsfeed%3F_%3D1328276903643

which contains &amp;redirectUrl= instead of &redirectUrl=

How do I pass this URL to window.location.href without the & being encoded to &amp; whilst maintaining the redirectUrl as an encoded URL string?

You need to get the Raw value so that it doesn't html encode the value.

@Html.Raw(Model.FacebookLoginUrl)

You are putting it inside javascript, and you'll want to escape anything that could goof up your javascript. So try this:

var redirectUrl = @Html.Raw(Json.Encode(Model.FacebookLoginUrl))

For your reference: Json class

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