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

后端 未结 8 921
鱼传尺愫
鱼传尺愫 2020-12-23 16:51

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

相关标签:
8条回答
  • 2020-12-23 17:19

    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>
    
    0 讨论(0)
  • 2020-12-23 17:23
    <ul>
    @foreach (var mi in Model.MenuItems) {
        <li@(mi.Selected?" class=\"selected\"":null)>
            <a href="@mi.Href" @{if(!string.IsNullOrEmpty(mi.Title)) { <text>title="@mi.Title"</text>} }>@mi.Text</a>
        </li>
    }
    </ul>
    

    I haven't tested it but it parses correctly.

    0 讨论(0)
提交回复
热议问题