4

Using Razor I want to conditionally wrap some content in a <span> element based on a boolean property of my model. My guess is that I will need to use Templated Razor Delegates, but I'm finding it tricky to get them right.

My model goes something like:

public class Foo
{
    public bool IsBar { get; set; }
}

and in my view I'd like to be able to use something similar to:

<a href="/baz">
    @Html.WrapWith(Model.IsBar, "span", @This content may be wrapped, or not)
</a>

where it would render:

<!-- Model.IsBar == True -->
<a href="/baz">
    <span>This content may be wrapped, or not</span>
</a>

<!-- Model.IsBar == False-->
<a href="/baz">
    This content may be wrapped, or not
</a>
4

2 回答 2

3

我总是用 span 包装内容,让 css 处理所有的表示逻辑,如果有的话

<a href="/baz">
    <span class="@(Model.IsBar ? "bar" : "")">This content may be wrapped, or not</span>
</a>

并将css规则应用于.bar

span.bar
{
   //some style rules
}
于 2012-05-21T14:56:29.713 回答
2

you could do an If in your editor Template view with Razor

@if(Model.IsBar)
{
      <span>This content may be wrapped, or not</span>
}
else
{
       This content may be wrapped, or not
}

UPDATE

or you could do your custom helper

@helper Foo(bool bar)
{
     @if(bar)
     {
      <span>This content may be wrapped, or not</span>
     }
     else
     {
       This content may be wrapped, or not
     }

}
于 2012-05-21T14:45:22.833 回答