Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concisely create optional HTML attributes with razor view engine?

I'm looking for a way to write the following code with less lines of code (maybe 5). I suppose I could do the same thing as the selected class but this razor syntax isn't looking pretty.

<ul> @foreach (var mi in Model.MenuItems) {   <li@(mi.Selected?" class=\"selected\"":null)>   @if (string.IsNullOrEmpty(mi.Title)) {     <a href="@mi.Href">@mi.Text</a>   } else {     <a href="@mi.Href" title="@mi.Title">@mi.Text</a>   }   </li> } </ul> 
like image 990
JarrettV Avatar asked Sep 27 '10 00:09

JarrettV


People also ask

What is Razor view 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.

How do you make a field required in Cshtml?

cshtml. Add the "[Required]" attribute to the field that you want to make mandatory for insertion. The required attribute requires the "System. ComponentModel.

What is difference between View and Razor view?

The Razor View Engine is a bit slower than the ASPX View Engine. Razor provides a new view engine with streamlined code for focused templating. Razor's syntax is very compact and improves readability of the markup and code. By default MVC supports ASPX (web forms) and Razor View Engine.


1 Answers

Fixed in ASP.NET MVC 4

see http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx

Conditional attribute rendering

If you have an attribute that might be null, in the past you've needed to do a null check to avoid writing out an empty attribute, like this:

<div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div> 

Now Razor is able to handle that automatically, so you can just write out the attribute. If it's null, the attribute isn't written:

<div class="@myClass">Content</div> 

So if @myClass is null, the output is just this:

<div>Content</div> 
like image 184
JarrettV Avatar answered Sep 19 '22 11:09

JarrettV