Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

asp.net mvc - 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>
question from:https://stackoverflow.com/questions/3800473/how-to-concisely-create-optional-html-attributes-with-razor-view-engine

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...