1. Original Entry + Comments2. Write a Comment3. Preview Comment

March 07, 2012  |  New for ASP.NET Web Pages: Better ~ operator support  |  13234 hit(s)

Another improvement in the Beta release of ASP.NET Web Pages v2 is better integration of the ~ operator. The ~ operator, as ASP.NET people know, resolves to the root path of the current website. (See also) This is handy for creating URL paths, because it means that a) you don't need to hard-code an absolute URL and b) it isn't relative to the location of the current page. You don't need to worry about how many folders up you need to count (e.g. ../../path) or about what happens if the current page moves.

In Web Pages v1 (as in all ASP.NET code), the ~ operator is supported. But it only works in server code; it's not supported in native HTML, so to speak. If you want to create a path that uses the ~ operator, you therefore have to wrap the path into something that tells ASP.NET that you've got server code. Inside of markup, we use the Href method. For example, to create an <a> link that incorporates it, you have to do this:

<a href="@Href("~/Default")">Home</a>

It works, but it's not very intuitive.

For v2 Beta, the .cshtml parser was enhanced so that it can recognize the ~ operator inline with normal markup. So the previous example can now be written like this:

<a href="~/Default">Home</a>

No need for the Href method any more. In .cshtml pages (not plain .html or .htm pages, of course), you really can treat the ~ operator as, in effect, pass-through HTML. I was working on something the other day that used a ~ path with inline server code, and it came out like this:

columns: grid.Columns(
grid.Column(format: @<a href="~/EditMovie?id=@item.ID">Edit</a>),
Slick. Every time now that I work with non-ASP.NET pages I wish I could use it there, too. :-)