Skip to content

Common Pattern in ASP.NET Razor For Clean cshtml Pages

Updated: at 11:18 PM

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