如何在「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);">
但上面的代碼是行不通的。
如何在「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);">
但上面的代碼是行不通的。
這應該工作,如果你使用的代碼塊
@if (condition) {…} else {…}
試試這個:
<a id="spnMarkButton" href="javascript:void(0);" @if(1==1) { <text>style="display:none;"</text> } else { <text>style="display:block;"</text> } onclick="MarkStore(@(storeRating.StoreId));">
你採取錯誤的做法。
在模型類,添加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);">
不要混合使用邏輯和標記。 ?
+1絕對正確! –
_Don't混合邏輯和標記_。這很有趣,因爲對於試圖將界面與邏輯分離的所有模式而言,這是真實的烏托邦。看看你的例子:你將CSS標記從標記移動到模型,這與你所說的完全相反。在我看來,這實際上是少數情況下邏輯內部標記似乎完全合理的情況之一。我的2美分:) – Joao
你可以做容易(:)運營商,或更好地輔助類:
@* 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類是在我看來,最徹底的方法。
是否有一個特定的原因,它爲什麼需要嵌入標籤?
@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);">
}
它不起作用...
你需要將自己的風格包裝在 標籤標籤即 style =「」 –
它也不起作用。 –