Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect from a view to another view

Hi I am trying to redirect from a view to a different view but I get a red squigly in visual studio.How can I redirect from inside a view to another view.This is what I have tryed but it does not work:

@Response.Redirect("~/Account/LogIn?returnUrl=Products"); 

How can I redirect from my curent view to another view?

like image 582
Nistor Alexandru Avatar asked Dec 29 '12 09:12

Nistor Alexandru


People also ask

How do I redirect from one view to another?

You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is: return RedirectToAction("Index", model); Then in your Index method, return the view you want.

How do I redirect to another view in HTML?

You should use controller to redirect request before creating model and passing it to view. Use Controller. RedirectToAction method for this.


2 Answers

It's because your statement does not produce output.

Besides all the warnings of Darin and lazy (they are right); the question still offerst something to learn.

If you want to execute methods that don't directly produce output, you do:

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");} 

This is also true for rendering partials like:

@{ Html.RenderPartial("_MyPartial"); } 
like image 89
NKCSS Avatar answered Sep 21 '22 09:09

NKCSS


That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:

public ActionResult SomeAction() {     ...     return RedirectToAction("SomeAction", "SomeController"); } 

Now since I see that in your example you are attempting to redirect to the LogOn action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize] attribute:

[Authorize] public ActionResult SomeProtectedAction() {     ... } 

Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl).

like image 26
Darin Dimitrov Avatar answered Sep 22 '22 09:09

Darin Dimitrov