Conditional render in Razor

Posted on Jan 17, 2015 by Morten Empeño

This small article shows you how you can easily show or hide a group of content based on a simple condition.

It is very easy to decide wether a certain part of html should be rendered, when developing MVC applications with razor views.

The syntax is as simple as:

@if (Condition)
    html to be rendered

Here is an example from a blog page. If the user is in a role named "canEdit", he should be presented with a "Create New" Action Link. 

A p tag with an action link is rendered, in case the user has the specific role.

@if (User.IsInRole("canEdit"))
        @Html.ActionLink("Create New", "Create")

Back to List