条件ASP.NET MVC剃刀部分

时间:2011-08-17 17:48:10

标签: asp.net-mvc asp.net-mvc-3 razor

我想仅在某些属性(Model.ReadOnly)为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 >
}

我尝试将其包裹在@if ( !Model.ReadOnly ) {}中,但它不起作用。

有办法做到这一点吗?


我不想定义空白部分(as @itsmatt suggests),我的页面布局会更改是否定义了部分(使用IsSectionDefined( "toolbar" ))。

3 个答案:

答案 0 :(得分:40)

这应该有用。

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

    }
    </text>
}

我从未说过它会很漂亮; - )

答案 1 :(得分:4)

这对我有用:

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

   }
}

基本上是在有条件的地方翻转。如果Model.ReadOnly为真,这实际上会导致空部分。


更新

那么,将该部分移动到PartialView并执行以下操作:

@Html.Partial("MyAction")
在您的视图中

然后让MyAction根据ReadOnly值返回相应的PartialView?类似的东西:

public PartialViewResult MyAction()
{
   ...

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

似乎这样可以正常工作。

答案 2 :(得分:0)

贝特朗,

请参阅:

Razor If/Else conditional operator syntax

基本上(para-phrasing),... Razor目前不使用@()支持C#表达式的子集,不幸的是,三元运算符不属于该集合。

另外,这可能是解决问题的方法:

conditional logic in mvc view vs htmlhelper vs action

基本上,使用if逻辑调用partialview以满足您的标准。

[edit] 这是我的基本思路(你的@section代码是在那部分中定义的):

@if(!Model.ReadOnly) 
{
    @Html.Partial("toolbar")
}
相关问题