簡體   English   中英

在Razor的“ a href”標簽中嵌入if語句

[英]Embed if statement inside a “a href” tag in Razor

如何將if語句嵌入“ a href”標簽中。

例如

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

但是上面的代碼不起作用。

您采用錯誤的方法。

在模型類中,添加如下所示的吸氣劑:

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

不要混用邏輯和標記。

為什么需要將其嵌入標簽中有特定的原因?

@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);">
}

如果使用代碼塊,這應該可以工作

@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));">

您可以使用(?:)運算符來簡化操作,也可以使用助手類來簡化操作:

@* 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"
    }
}

我認為助手類是最干凈的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM