2
votes

I have action in controller with ASP.NET MVC 5 attribute routing.

[RoutePrefix("ControllerName")]
public class MyController : Controller
{
    [Route("ActionName")]
    public ActionResult Index()
    {
        return View();
    }
}

When I try to get url in action like this (Controller.Url)

Url.Action("Index", "My")

I get

/My/Index

When I do the same in View (It's WebViewPage.Url),

@Url.Action("Index", "My")

I get

/ControllerName/ActionName

How can I get /ControllerName/ActionName in action?

2

2 Answers

2
votes

If you want to construct the url from other controllers, you need to make use of the UrlHelper class like this:

var urlHelper = new UrlHelper(ControllerContext.RequestContext);
var url = urlHelper.Action("Index", "My");

This would construct your desired result: /ControllerName/ActionName

0
votes

Try this:

Url.Action("Index", "My")

You need to use only part before Controller as a your controller name. Do the same for @Url.Action in views.