Razor conditional attribute and formatting

Razor provides all the option to format the data as well as conditional attributes, even it is more powerful than we had earlier in asp.net. In this article we will try to see some commonly used conditional attribute tricks, formatting of data like apply class conditionally, show hide controls, enable and disable the controls. How to use icons as link in WebGrid, add HTML to the column, formatting the data in column etc.

Conditional Rendering:

if IsActive then render textbox normally otherwise make it disabled

// By using simple if else
@if (Model.IsActive) { 
    @Html.TextBoxFor(model => model.CategoryName, new { @class = "text" })
    @Html.TextBoxFor(model => model.CategoryName, 
               new { @class = "text", @disabled ="disabled" })

// By using ternary operator    
@Html.TextBoxFor(model => model.CategoryName,
    @Model.IsActive ? (object)new {@disabled = "disabled" } : new {})

// To make readonly is easy
@Html.TextBoxFor(model => model.CategoryName, new { @readonly = @Model.IsActive })

Conditional Class:

Conditionally use the class otherwise nothing

<div class="@className"></div>
//When className = null

// When className = ""
<div class=""></div>

//When className = "my-class"
<div class="my-class"></div>

Alternate row class by using the row number or index. if row is 1, 3, 5.... apply class1 and else class2. I used simple div while we can use tr td for table.

@foreach(var itme in Model.Person){
    <div class="@(item.Index % 2 == 0 ? "class1" : "class2")">
        @item.FirstName @item.LastName @item.City 

How to format date in Razor:

We can format date either into the model or in view itself, if we format in model then now need to format in view and it is good practice to use because it will show the same format in entire application. It is also easy to maintain, suppose our client change his mind as always they do, to change the date format then we don't need to check entire application but directly we can do it in model.

// In Model
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy hh:mm:ss tt}")]
public DateTime CreatedOn { get; set }

// In View Razor, if formatted in model
@Html.DisplayFor(m => m.CreatedOn) 

// In View Razor, if not formatted in model
@Model.CreatedOn.ToString("MM/dd/yyyy hh:mm:ss tt")

Format number, decimal & currency:

To format number to separate with comma, there is nothing new we can use the same logic like asp.net same is true for currency and decimal, let's see with some examples by using number, decimal and currency

 // Number: 1,234,567
 Number: @Html.Raw(String.Format("{0:#,##}", 1234567))

 // Decimal: 1234.567 => 123.57
 Decimal: @Html.Raw(String.Format("{0:#.##}", 1234.567))

 // Currency: $1,234,567.00
 Currency: @Html.Raw(String.Format("{0:C}", 1234567))

For more detail see Standard Numeric Format Strings

To Activate the menu:

Razor v 2.0 introduce feature, called Conditional Attributes, and it allows you to decide whether to render the attribute at all or not. Let's say we want to activate the menu by using class "menu-active".

<ul class="nav navbar-nav">
    <li>@Html.ActionLink("Home", "Index", "Home", new { @class = IsPage("index") })</li>
    <li>@Html.ActionLink("About", "About", "Home", new { @class = IsPage("about") })</li>
    <li>@Html.ActionLink("Help", "Help", "Help", new { @class = IsPage("help") })</li>

// Add the function somewhere on the _layout view
@functions {
  public static string IsPage(string pageName)
    return HttpContext.Current.Request.Url.ToString()
                .ToLower().Contains(pageName) ? "menu-active" : null;

Init Caps:

How to capitalize the first letter, say we want to show the city name so it's first letter should be capitalized, and how we can do the same in WebGrid

// Anywhere in view

// In webgrid
grid.Column("City", header: "City", 
   </text> ,style: "someclass"),    

Boolean attributes: Like checkbox checked, radio button selection etc.

<input type="checkbox" checked="@isChecked" />


//When isChecked = true
<input type="checkbox" checked="checked" />

//When isChecked = false
<input type="checkbox" />

Let us know if you have any better solution or any question which can help others.

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • razor
  • mvc
  • formatting
By Ali Adravi On 14 Mar, 15  Viewed: 11,983

Other blogs you may like

Different action for different buttons from a single page in MVC

To post from different buttons on a single MVC page to different action methods, we need some extra code. We need to create an attribute class by inheriting ActionNameSelectorAttribute and override IsValidName method. We will use the button name to call any particular action on the basis of button... By Ali Adravi   On 26 Apr 2015  Viewed: 3,269

ActionResult VS ViewResult in MVC

In MVC controls there are different type of action result we use as a return type from a controller action method in which ViewResult, ActionResult and JsonResult are commonly used. In this article we will learn what are the available action results and which one we need to use in which... By Ali Adravi   On 19 Jul 2013  Viewed: 3,266

Action filter basics in ASP.Net MVC

Action filter in MVC is from very first version. Sometimes we want to perform logic before or after calling the action method, to support this MVC provides action filters. Action filters are used as attributes. Filter can be applied on action method or directly to the controller. Suppose we want... By Hamden   On 13 Jul 2013  Viewed: 1,154

How to create a single thanks page for entire controller in MVC

Sometimes we need a thanks page say we have user registration, change password, activate account functionality in our application then we need a thanks page after registering with our site, to say thanks for registering with us or showing confirmation that your password is successfully changed or... By Hamden   On 30 Jun 2013  Viewed: 2,922

MVC jquery autocomplete with value and text field

In MVC, autocomplete with jquery is the best way to pull data from database and render according to our requirements, so in this article we will use jquery to show the auto complete text box without any ajax controls. We need a method to get the data from database, a controller method to handle the... By Ali Adravi   On 29 Jun 2013  Viewed: 5,742