If/Else Statements in MVC3 With Razor

In ASP.NET MVC2, if we wanted to write some conditional view code (such as displaying a link if a user is logged in), we could do it like so:


<% if (User.Identity.IsAuthenticated) { %>
<%= "Your XYZ is " + ... %>
<% } else { %>
<%= "[not logged in]" %>
<% } %>

How do we “translate” this into a Razor-style if-statement? Very simply:

@if (User.Identity.IsAuthenticated) {
  Your XYZ is ...
} else {
  [not logged in]
}

What’s cool about this is a complete lack of <% and %>! This is precisely what Scott Guthrie mentioned in his introduction to MVC3 that Razor enables a very fluid coding flow. You don’t need to stop and think about where to write angle brackets; you just write code, write presentation logic, and it works!

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Libraries, Web and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>