Orchard CMS TutorialsOrchard Websites, Modules, Widgets, and Themes

ASP.NET MVC 4 - The New Tilde Slash Feature in Razor 2

Razor 2 in ASP.NET MVC 4 has a very subtle enhancement that allows you to dump the old Url.Content("~/...") or @Href("~/...") when specifying relative paths in your Razor Pages and just use "~/". This doesn't seem like much, but it really eliminates a lot of noise in your Razor Views. It also probably cuts down on errors for those in the habit of typing "~/" in their paths anyway forgetting to use Url.Content or something similar.

Razor 2 and "~/" in ASP.NET MVC 4

To check out this new Razor 2 Feature just create a new ASP.NET MVC 4 Internet Application in Visual Studio and take a peek at the _Layout.cshtml file. Inside the head of the layout view you will find a reference to the favicon file using the Tilde Slash Feature.

<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />

Notice the lack of @Url.Content or @Href that helps convert the virtual path of the favicon file to the application's absolute path. Now you can just type in the "~/..." in the reference and Razor will convert it for you. Looking at the source of the view in your browser shows that indeed this relative path was converted to an absolute path by Razor 2:

<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />

Simple and clean without all the noise!

Conclusion

David Hayden is an ASP.NET MVC and Orchard CMS Developer with 18 years experience developing ASP.NET websites and related technologies. As a 7-year Microsoft MVP, he founded the Tampa ASP.NET MVC Developer Group and Sarasota Web Developer Group which taught and promoted ASP.NET MVC web development to Microsoft .NET Developers. In addition to ASP.NET MVC, David has been developing Orchard themes, modules, widgets, and websites for two years. He's contributed bug fixes and enhancement to several versions of Orchard and has published modules in the Orchard Gallery. He attended the first Harvest Orchard Developer Conference and has created over 100 Orchard themes and 300+ Orchard modules in the past two years.

Contact Me

I build affordable and exceptional websites based on Orchard CMS. If you are interested in upgrading your existing website, creating a new website, or looking for a custom Orchard Theme or Orchard Module, please email me.