Redirecting to Different Controllers in ASP.NET MVC
Last year, we started using ASP.NET MVC at work and are still learning its intricacies. About a month ago, I needed to put in a button that redirected to another part of the application. I have sanitized the details because they aren't germane. The button was located on a page controlled by a different controller than the page I wanted to redirect to. I tried the following 3 incorrect snippets before seeing the error, which is corrected in the last snippet.
Can you spot the difference? Some of our MVC actions perform operations on the server with no need for a return value. But the redirect needs a return value to switch views. So I needed to have a function with a return statement.
<HttpPost()> _
<ActionName("Index")> _
<HandlesButton("redirectingaction")> _
Public Sub RedirectToOtherController()
Redirect("OtherController.ashx/NewAction")
End Sub
<HttpPost()> _
<ActionName("Index")> _
<HandlesButton("redirectingaction")> _
Public Sub RedirectToOtherController()
Redirect("~/OtherController.ashx/NewAction")
End Sub
<HttpPost()> _
<ActionName("Index")> _
<HandlesButton("redirectingaction")> _
Public Sub RedirectToOtherController()
RedirectToAction("NewAction", "OtherController")
End Sub
Can you spot the difference? Some of our MVC actions perform operations on the server with no need for a return value. But the redirect needs a return value to switch views. So I needed to have a function with a return statement.
<HttpPost()> _
<ActionName("Index")> _
<HandlesButton("redirectingaction")> _
Public Function RedirectToOtherController() As ActionResult
Return RedirectToAction("NewAction", "OtherController")
End Function