Sandhya
Sandhya

Reputation: 5

Asp.net MVC redirect Url to another controller view

I am very new to MVC and trying to migrate asp.net application to MVC. Basically I am trying to reuse the code where ever possible. In one case I was trying to use Redirect("SomeUrl") and it works pretty well with the view under same controller.

For eg., I added below piece of code in HomeController.cs

public ActionResult Login()
{
 return Redirect("HomeMgr?Section=home&Type=Mgr");
}

Well, could someone suggest me if I can use Redirect(Url) to redirect to a view in another Controller? is there any format for Url something like

"~/controllername/Viewname?something=something&something=otherthing"

(I've read in other posts that I can achieve this using RedirectToAction, but I am trying not to change existing code which uses querystring values. )

Upvotes: 0

Views: 1179

Answers (2)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93464

Don't use Redirect to redirect to Actions in your app. There are several reasons for this. First, it's just simpler to user RedirectToAction as Alundra's answer provides. However, simpler is only part of the answer.

There's a problem with using Redirect. And that has to do with the way Routing works in MVC. In MVC, you can reach the same action via multiple different URL's. For instance, in a default MVC template, the following are all valid URL's.

http://yoursite/
http://yoursite/Home
http://yoursite/Home/Index

Now, what happens when you use Redirect? If you use the last url, it will work fine. You'll end up with the following url.

http://yoursite/Home/HomeMgr?Section=home&Type=Mgr

But if you're at any of the others, you have a problem...

http://yoursite/HomeMgr?Section=home&Type=Mgr

Oops... that won't work... That will be looking for a controller named HomeMgrController.

You get the same at the root as well.

Using RedirectToAction solves this problem, as it takes your routing into account and will figure out the correct url to redirect you to based on the Controller and Action you specify.

Upvotes: 1

IndieTech Solutions
IndieTech Solutions

Reputation: 2539

return RedirectToAction("ActionName", "ControllerName", new { Section=home,Type=Mgr ......Anythingelse you want to pass  });

Upvotes: 1

Related Questions