December 06 2013

ASP.net MVC Razor if else statement display output

Tagged Under :

asp.net
Not all content container blocks start with a tag element tag, though, and there are scenarios where the Razor parser cannot implicitly detect a content block.

Razor addresses this by enabling you to explicitly indicate the beginning of a line of content by using the @: character sequence within a code block. The @: sequence indicates that the line of content that follows should be treated as a content block:
@if (someCondition) {
  @: Some content to display...
}

For more practical example, the below snippet demonstrates how we could output a "Not Stock" message to our product if numbers of product is zero.
@model.product_name
@if (model.unit_stock == 0) {
  @: Not Stock
}

Because I am not wrapping the "Not Stock" message in an HTML tag element, Razor can’t implicitly determine that the content within the @if block is the start of a content block. We are using the @: character sequence to explicitly indicate that this line within our code block should be treated as content.

For multiple lines content
Razor makes it easy to have multiple lines of content wrapped in an HTML element. For example, below the inner content of our @if container is wrapped in an HTML <p> and <text> element – which will cause Razor to treat it as content:
@if (someCondition) {
  <p>
    Today: @DateTime.Now
    Content Line 1
    Content Line 2
  </p>
}
OR
@if (someCondition) {
  <text>
    Today: @DateTime.Now
    Content Line 1
    Content Line 2
  </text>
}

Make a Comment

You must be logged in to post a comment.