3

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 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Good point - minor bug when creating an example. I have corrected it. Still looking for answers to the question. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.