Reputation: 1449
Im developing a project with ASP.NET Core 2.2 MVC. Here is a view named MyView in which there is a link which calls MyAction action.
<div>
<a asp-controller="Home" asp-action="MyAction">my link</a>
</div>
And this is MyAction which does st.
public async Task<IActionResult>MyAction(argument1,argument2)
{
if(a condition)
{
it should redirect me to the view which *MyLink* is placed there.
}
else
{
return false;
}
}
I want to know how can I find the url of the view(page) which called MyAction and redirect to it.
This is project structure(I made it simple)
I found this. But I want to add NOTHING to the destination action. It doesn't work in .NET Core
How do I redirect to the previous action in ASP.NET MVC?
Upvotes: 1
Views: 6839
Reputation: 514
You can use title or specific id for every page. After you assigned ViewData["Title"] in the view (or you can use specific id for everypage without assigning title)
@{
ViewData["Title"] = "MyView";
}
<div>
<a asp-controller="Home" asp-action="MyAction" asp-route-returnUrl="@ViewData["Title"]" >my link</a>
</div>
Then you can use it in action
public async Task<IActionResult>MyAction(string returnUrl)
{
return View(returnUrl)
return RedirectToAction(returnUrl,"YourAction")
}
If you are gonna do something different use switch case for the reminder string like (redirecttoaction or whatever you like)
switch (returnUrl)
{
case"MyView":
.....
break;
case "YourView":
.....
break;
default:
...
break;
}
Upvotes: 3
Reputation: 1449
I did it. Here is how you can redirect to the view which called the action. Mayak provided a good solution for it. I just added some extra information to make it secure. As he/she said, first,you should assign Title to all Views.
And after that you should pass Path and QueryString Via asp-route-returnUrl.
@{
ViewData["Title"] = "MyView";
}
<div>
<a asp-controller="Home" asp-action="MyAction" asp-route-returnUrl="@string.Format("{0}{1}",Context.Request.Path, Context.Request.QueryString)" >my link</a>
</div>
Then in MyAction we pass the returnUrl as an argument
public async Task<IActionResult>MyAction(string returnUrl)
{
if(everything is alright)
{
return LocalRedirect(returnUrl);
}
else
{
return false;
}
}
There is something called open redirect attack
https://learn.microsoft.com/en-us/aspnet/core/security/preventing-open-redirects?view=aspnetcore-2.2
When your application receives data from a form. It's not secure and data can potentially be tampered with to redirect users to an external, malicious URL. So by using LocalRedirect you can prevent open redirect attacks.
Upvotes: 3