ASP.NET MVC3 / Razor: How to Get Just the Uri for an Action Method

I normally wouldn’t post something this small to my blog, but this issue bothered me so much when I was working on some Twitter @Anywhere + jQuery integration in ASP.NET MVC3 that I couldn’t help but share it.

Issue: You’re using ASP.NET MVC3 and want to be able to place a relative Uri for one of your ASP.NET MVC controller’s action methods in a block of JavaScript or anywhere else, and you want to be able to do it without having to parse it out of an Html.ActionLink output or anything else. What built-in helper method do you use?

Solution: The answer is that you use the Url.Action method, which yields a relative Uri, as you’d expect.

Observe the code below:

T("#login").connectButton({
	authComplete: function (user) {
		// triggered when auth completed successfully
		$.post('@Url.Action("AnywhereTest", "Auth")');
		location.reload();
	   
	}
});

And here’s the output to go along with it:

T("#login").connectButton({
	authComplete: function (user) {
		// triggered when auth completed successfully
		$.post('/auth/anywheretest');
		location.reload();
	   
	}
});

Discussion, links, and tweets

I'm the CTO and founder of Petabridge, where I'm making distributed programming for .NET developers easy by working on Akka.NET, Phobos, and more..