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

April 11, 2012  |  Two small ASP.NET Web Pages (Razor) syntax tips  |  17225 hit(s)

Two tips for Razor syntax: using a conditional attribute to set the selected attribute in a list item; working around a syntax restriction on x@x (e.g. <h@level>).

Tip 1
When I wrote recently about conditional attributes in ASP.NET Web Pages version 2 (new for that version), the example was the checked attribute of a checkbox. What about dynamically selecting an item in a <select> list?

I wanted the <select> list to remember the user’s choice after the page had been submitted. In an <input> element, you can do this by setting the value attribute to the appropriate item in the Request collection:

<input type="input" name="firstName" value="@Request.Form["firstName"]" />

In my case, I'm populating the <select> list from a database query (i.e. a collection) using a foreach loop. So I can use this code to compare each item against the user's most recent selection and set the selected attribute conditionally:

<select name="selectGenre">
@foreach(var row in db.Query("Select DISTINCT Genre FROM Movies ORDER BY Genre")){
As each row is processed, I compare its Genre property/field against whatever was selected for the last page submission. If there's a match, the comparison returns true and the selected attribute is rendered.

(In the actual app, I'm sticking the results of the query into a variable that I in turn cache, so it's not quite as ineffecient as running a query every time the page runs. :-) )

Tip 2
This one was raised as a question by MVP Kris van der Mast, and might already be noted elsewhere. Kris wanted to set a heading level dynamically (e.g., <h1>, <h2>, etc.) which he tried by using the syntax <h@level>, where level is a variable.[1] In particular, he was using this syntax with success in Web Pages v1 (or possibly in a preview version of v1), but it definitely wasn't working with Web Pages v2.

It turns out Kris's original syntax was not supposed to work, and this had been fixed up for v2. The issue is that any string of the form x@x (e.g., <h@level>) is supposed to be interpreted as an email address. (In the words of one of the developers, this detection is "admittedly basic.") For a situation like Kris's, the syntax that works is x@(x) — for example, <h(@level)>. The parentheses foil the email-address detection and are otherwise of course benign.

[1] Maybe he didn't want to do this thing specifically, but it was a good example for this purpose.