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>
class
attribute would not be rendered by Razor if value isnull
I've come up with a chainable HtmlAttribute class and some Html Extension methods to allow the Razor syntax below:
Here is the HtmlAttribute class:
Extra info: The "seperator" is used to chain together multiple values for an attribute. This can be useful for multiple css class names (use a space) or perhaps use String.Empty to build an value dependant on multiple conditions (by using the .Add() method)
And here are the Html Extension helper methods:
Let me know if they are of use.
Thanks,
Lee
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:
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:
So if @myClass is null, the output is just this:
I haven't tested it but it parses correctly.
It's really pretty simple and clean: