Injecting Conditional HTML and Content Blocks with ASP.NET MVC Razor

I have been working recently with ASP.NET MVC 3 and the Razor view engine. For part of the work I’m doing, I need to send some content to the browser based upon certain conditions. I described a couple of ways to do this before in this post and this post and I wanted to share another pattern I use to output entire HTML or other blocks of content.

When you need to render an entire block of content like a <div> depending on a condition, look at using a simple if statement to decide whether to output the entire content block. In the example below, we test to see if a ViewBag value is populated and only render the content if the condition is met. Otherwise, nothing is rendered and the block is left out.

[sourcecode language=”html”]

@if (ViewBag.SomeValue != null && ViewBag.SomeValue.Length > 0)
<div id=”myMessage”>@ViewBag.SomeValue</div>


Comments are closed.

Sign in
Forgot password?
Sign up

(*) Required fields

I agree with OptimaSales Terms & Privacy Policy