24

I want to define this section only if some property (Model.ReadOnly) is false.

@section toolbar {
    <div class="tool">
        <div class="row">
            @Html.ActionLink( Resources.Strings.Edit, "Edit", "Profile" )
        </div>
        <div class="row">
            @Html.ActionLink( Resources.Strings.Delete, "Delete", "Profile" )
        </div>
    </div >
}

I tried wrapping it up in @if ( !Model.ReadOnly ) {} but it doesn't work.

Is there a way to do this?


I do not want to define an empty section (as @itsmatt suggests), the layout of my page changes whether the section is defined or not (using IsSectionDefined( "toolbar" )).

Community
  • 1
  • 1
Bertrand Marron
  • 21,501
  • 8
  • 58
  • 94

3 Answers3

44

This should work.

@if (!Model.ReadOnly)
{
    <text>
    @section toolbar {

    }
    </text>
}

I never said it would be pretty ;-)

Charlino
  • 15,802
  • 3
  • 58
  • 74
4

This works for me:

@section SomeSection {
   @if (!Model.ReadOnly)
   {

   }
}

Essentially flipping where the conditional is. This essentially results in an empty section if Model.ReadOnly is true.


Update:

So, what about moving that section to a PartialView and doing something like:

@Html.Partial("MyAction")

in your View and then let the MyAction return you the appropriate PartialView based on the ReadOnly value? Something like:

public PartialViewResult MyAction()
{
   ...

   // determine readonly status - could have passed this to the action I suppose    
   if (ReadOnly)
   {
      return PartialView("TheOneThatDefinesTheSection");
   }
   else
   {
      return PartialView("TheOneThatDoesNotDefineTheSection");
   }
}

Seems like that would work just fine.

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
itsmatt
  • 31,265
  • 10
  • 100
  • 164
0

Bertrand,

See:

Razor If/Else conditional operator syntax

basically (para-phrasing), ... Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

also, this may be a way around the issue:

conditional logic in mvc view vs htmlhelper vs action

basically, use the if logic to call a partialview to satisfy your criteria.

[edit] this was my basic thinking (where your @section code is defined in that partial):

@if(!Model.ReadOnly) 
{
    @Html.Partial("toolbar")
}
Community
  • 1
  • 1
jim tollan
  • 22,305
  • 4
  • 49
  • 63
  • I don't think you understood me. I'm not asking how `if` statements work. I'm trying to define a section **only** if a condition is verified. I don't know where you got that I want to use a ternary operator. – Bertrand Marron Aug 17 '11 at 18:00
  • ok -no worries, just covering all the bases. i still 'think' my idea of defining the toolbar @section in a partial view and then checking that may work (or not!!)... [see my clumsy edit] :) – jim tollan Aug 17 '11 at 18:11