Common Pattern in ASP.NET Razor For Clean cshtml Pages

I’ve been doing a lot of work over the past year in Microsoft’s ASP.NET Razor.  I’m not an html wizard and definitely a razor syntax wizard, but I have figured out a way that saves me time over and over.  It’s basically the same pattern of thinking that has me often do things in 2 or 3 steps instead of one just to make sure the logic is overly clear.

In this case, I often find myself trying to create complex Razor syntax to output data.  That is, say I want to output a link that combines a static URL with a dynamic one coming from a model.  My first work is almost always trying to do it all at once and I’m guessing at least someone is going to tell me how I could have done.  That is, I want something like (in non-working syntax):

<div class="more">
  <a href='""@(session.SessionUrl)"'>
          Read more</a>

So, the above does not work, but by sticking in some real C# code the following does (of course).

 <div class="more">
      var workshopUrl = "" +
   <a href="@(workshopUrl)" target="_blank" >Read more</a>

In production, I’ve added a little more error checking but you get the idea.  When I first started using Razor, my thinking was I did not liking using @{} type syntax because if felt like I was putting code in views.  Now, I’m not fooled anymore.  It is.

Feel free to add some comments here and let me know your thoughts. I’m always trying to figure out a better way to build razor pages that is both clear and correct.



The running program

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP since 2007. In addition, he’s a multi-course video author at Pluralsight. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


  1. Hmm, not sure how to post code in comments, but the href attribute should have been:


  2. The extra quotes look incorrect. You should remove the single quotes and the extra non-matching double quote in the middle so it looks like this instead:

    Read more


Get every new post delivered to your Inbox

Join other followers: