2013-05-30 18 views
2

如何在「a href」標籤內嵌入if語句。如果在Razor的「a href」標籤中嵌入語句

例如像

<a id="spnMarkButton" href="javascript:void(0);" @if(condition here) style="display:none;" else style="display:block;" onclick="MarkStore(@storeRating.StoreId);"> 

但上面的代碼是行不通的。

回答

5

你採取錯誤的做法。

在模型類,添加getter這樣的:

string MarkButtonDisplay 
{ 
    get 
    { 
     if(condition here) 
      return "none"; 
     else 
      return "block"; 
    } 
} 

並更改標記來:

<a id="spnMarkButton" href="javascript:void(0);" style="display: @Model.MarkButtonDisplay;" onclick="MarkStore(@storeRating.StoreId);"> 

不要混合使用邏輯和標記。 ?

+0

+1絕對正確! –

+1

_Don't混合邏輯和標記_。這很有趣,因爲對於試圖將界面與邏輯分離的所有模式而言,這是真實的烏托邦。看看你的例子:你將CSS標記從標記移動到模型,這與你所說的完全相反。在我看來,這實際上是少數情況下邏輯內部標記似乎完全合理的情況之一。我的2美分:) – Joao

0

你可以做容易(:)運營商,或更好地輔助類:

@* Inline with MvcHtmlString *@ 
<a id="spnMarkButton" href="javascript:void(0);" @(Model == null ? new MvcHtmlString("style=\"display:none;\"") : new MvcHtmlString("style=\"display:block;\""))>My link 1</a> 

@* Inline with Html.Raw *@ 
<a id="spnMarkButton" href="javascript:void(0);" @(Model == null ? Html.Raw("style=\"display:none;\"") : Html.Raw("style=\"display:block;\""))>My link 2</a> 

@* Using helper class - cleanest *@ 
<a id="spnMarkButton" href="javascript:void(0);" @RenderDisplayStyle()>My link 3</a> 

@helper RenderDisplayStyle(){ 
    if (Model == null) 
    { 
     @:style="display:none" 
    } 
    else 
    { 
     @:style="display:block" 
    } 
} 

Helper類是在我看來,最徹底的方法。

1

是否有一個特定的原因,它爲什麼需要嵌入標籤?

@if(condition here) 
{ 
    <a id="spnMarkButton" href="javascript:void(0);" style="display:none;" onclick="MarkStore(@storeRating.StoreId);"> 
} 
else 
{ 
    <a id="spnMarkButton" href="javascript:void(0);" style="display:block;" onclick="MarkStore(@storeRating.StoreId);"> 
}