Navigation and service panel


Content

Get url for area controller action from a View Rendering

By Kevin Brechb├╝hl on 4. February 2015, No comments

Sitecore doesn't support Mvc Areas out of the box, but of course we can use these anyway. This post shows how to resolve an url for a controller action from a Sitecore View Rendering within an area.

There are plenty of solutions from the community how to work with areas in Sitecore, but for this case we don't need any Sitecore customizations and only use the areas to structure our solution. Let us assume that we have multiple areas in our Visual Studio Solution, one might be MyArea. So in our area we have a view ViewRendering.cshtml, which we have defined within Sitecore as a View Rendering with the following path:

/Areas/MyArea/Views/ViewRendering.cshtml

In the same area we also have a Mvc controller MyController, with an action MyAction which returns some markup. In the View Rendering we want to create an ajax request to this controller action. This use case requires us to resolve the url from our controller action. In ASP.net Mvc this can be done very simple with the UrlHelper class:

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

But the url generated seems to be wrong:

/api/sitecore/My/MyAction

Why this? The answer is quite simple. Every View Rendering uses the SitecoreController to render itself, and this controller is not in our area. This means, that we are actually not in the context of our area and therefor the url is generated with the default route of Sitecore. What happens when we call this url? Yeah, it works :) The dynamic url resolving from Sitecore makes it possible.

But I'm not so happy with this, as we have defined another route for our area:

MyArea/{controller}/{action}/{id}

As you can see there are tokens for {controller} and {action} in the route. All these tokens can also be used in the @Url.Action() call. And yes, there is also a token {area}. So let's try to resolve the url with this call:

@Url.Action("MyAction", "My", new { area = "MyArea" })

Now you see the desired url /MyArea/My/MyAction. And also this call works perfectly.

Obviously this is not absolutely necessary, but I would recommend doing it correctly.

Categories  ASP.NET MVC  Best Practice Tags  Mvc  Url  Areas

No comments

Add your comment

Your email address will not be published. Required fields are marked *

*