How to embed if statement inside an "a href" tag.
Like for example
<a id="spnMarkButton" href="javascript:void(0);" @if(condition here) style="display:none;" else style="display:block;" onclick="MarkStore(@storeRating.StoreId);">
But the code above is not working.
You're taking the wrong approach.
In the model class, add a getter like this:
string MarkButtonDisplay
{
get
{
if(condition here)
return "none";
else
return "block";
}
}
And change the markup to:
<a id="spnMarkButton" href="javascript:void(0);" style="display: @Model.MarkButtonDisplay;" onclick="MarkStore(@storeRating.StoreId);">
Don't mix logic and markup.
Is there a specific reason it why it needs to be embedded in the tag?
@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));">
You can do easy with (?:) operator, or better with helper class:
@* 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 class is cleanest way in my opinion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.