Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional HTML Attributes using Razor MVC3

The variable strCSSClass often has a value but sometimes is empty.

I do not want to include an empty class="" in this input element's HTML, which means if strCSSClass is empty, I don't want the class= attribute at all.

The following is one way to do a conditional HTML attribute:

<input type="text" id="@strElementID" @(CSSClass.IsEmpty() ? "" : "class=" + strCSSClass) /> 

Is there a more elegant way of doing this? Specifically one where I could follow the same syntax as is used in the other parts of the element: class="@strCSSClass" ?

like image 569
tony722 Avatar asked Nov 09 '11 07:11

tony722


People also ask

How do you write if condition in razor view?

The If Condition The if statement returns true or false, based on your test: The if statement starts a code block. The condition is written inside parenthesis. The code inside the braces is executed if the test is true.

What is razor in HTML?

Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.

Does MVC use razor?

Razor is one of the view engines supported in ASP.NET MVC. Razor allows you to write a mix of HTML and server-side code using C# or Visual Basic.

What is razor in MVC What are the main Razor syntax rules?

Razor is a simple programming syntax for embedding server code in web pages. Razor syntax is based on the ASP.NET framework, the part of the Microsoft.NET Framework that's specifically designed for creating web applications.


1 Answers

You didn't hear it from me, the PM for Razor, but in Razor 2 (Web Pages 2 and MVC 4) we'll have conditional attributes built into Razor(as of MVC 4 RC tested successfully), so you can just say things like this...

<input type="text" id="@strElementID" class="@strCSSClass" /> 

If strCSSClass is null then the class attribute won't render at all.

SSSHHH...don't tell. :)

like image 170
Erik Porter Avatar answered Oct 08 '22 10:10

Erik Porter