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>
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.
cshtml. Add the "[Required]" attribute to the field that you want to make mandatory for insertion. The required attribute requires the "System. ComponentModel.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With