Reputation: 163
I'm trying to call a method from another controller using RedirectToAction()
. But it doesn't work. Could you please explain, what I'm doing wrong?
[HttpPost]
public ActionResult AddToWishList(int id, bool check)
{
var currentUser = WebSecurity.CurrentUserId;
if (currentUser != -1)
{
// ...
}
else
{
return RedirectToAction("Login", "Account");
}
}
I call the method in HTML:
<script>
$(document).ready(function () {
/* call the method in case the user selects a checkbox */
$("#checkbox".concat(@Model.Id)).change(function () {
$.ajax({
url: '@Url.Action("AddToWishList", "Item")',
type: 'POST',
data: {
id: '@Model.Id',
check: this.checked
}
});
});
});
It works if I use:
success: function (result) {
window.location.href = "@Url.Content("~/Account/Login")";
}
But I don't need to navigate to the Login() after every click, only if the user is not authorized. Could you please explain how I can use redirect in the controller?
Upvotes: 5
Views: 2138
Reputation: 25907
To add to @Win's answer - I had a use case where I had a legacy ASPX file in my ASP.NET MVC application. And, I had to navigate to that ASPX page from my MVC action returning ActionResult
. So, I did something like this to navigate to that ASPX page from my action. I had to create an absolute URL for navigation.
var myLegacyPageUrl = Request.Url.Scheme
+ "://"
+ Request.Url.Authority
+ Url.RequestContext.HttpContext.Request.ApplicationPath
+ "/mylegacypage.aspx?";
return JavaScript(string.Format("window.location='{0}'", errorPageUrl));
Hope someone finds it useful in case of legacy web pages present in modern MVC website.
Upvotes: 0
Reputation: 62260
You can response JavaScript which basically returns JavaScriptResult.
[HttpPost]
public ActionResult AddToWishList(int id, bool check)
{
return JavaScript("window.location='/Account/Login'");
}
Upvotes: 8