Home > Back-end >  How to redirect to action when action contains route attribute
How to redirect to action when action contains route attribute

Time:12-18

Controller

public class TestController{
   
   [Route("TestIndex")]
   public ActionResult Index(){
   }
}

html

<a href="@Url.Action("Index","TestController")">Go to test</a>

I have above code!!

On Go to test click I want to redirect to Index action of Testcontroller for that I used below code

href="@Url.Action("Index","TestController")"

but I think as route attribute is used there that's why it is not redirecting to that action

Thank you in advance

CodePudding user response:

ASP.NET has built in methods for this such as RedirectToAction See https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.redirecttoaction?view=aspnet-mvc-5.2

A usage would look like: return RedirectToAction("controller", "method");

To pass route attributes simply use:

return RedirectToAction("controller","method", new { id });

If that doesn't work either try using: RedirectToAction with parameter

return RedirectToAction( "Main", new RouteValueDictionary( 
    new { controller = controllerName, action = "Main", Id = Id } ) );

As some people have noted the other example not working for them.

CodePudding user response:

you have a bug in your code, should be

<a href="@Url.Action("Index","Test")">Go to test</a>

or maybe

<a href="@Url.Action("TestIndex","Test")">Go to test</a>

You have to use something one - absolute route, or relative. Since you didnt post a controller route and your config endpoints, I can not understand what route you really need, but try this, it will certainly work

<a href="~/test/testIndex">Go to test</a>

and route

 [Route("~/Test/TestIndex")]
   public ActionResult Index(){
   }
  • Related