Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional ASP.NET MVC razor sections

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" )).

like image 753
Bertrand Marron Avatar asked Aug 17 '11 17:08

Bertrand Marron


2 Answers

This should work.

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

    }
    </text>
}

I never said it would be pretty ;-)

like image 174
Charlino Avatar answered Oct 22 '22 14:10

Charlino


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.

like image 28
itsmatt Avatar answered Oct 22 '22 15:10

itsmatt