Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap content with link if condition = true?

Tags:

c#

asp.net

razor

What is the best way to wrap some elements inside a link, if a condition is true?

So, lets say i have this markup:

<div>
   <h1>Header</h1>
   <span>Subheader</span>
   <p>Lorem ipsum</p>
</div>

If i have a condition == true, then the whole above markup should be wrapped in a link, like so:

<a href="#">
    <div>
       <h1>Header</h1>
       <span>Subheader</span>
       <p>Lorem ipsum</p>
    </div>
</a>

This is in Razor/C# code. What is the best way, without dublicating the markup?

like image 334
brother Avatar asked Jan 18 '26 09:01

brother


2 Answers

Maybe a little less hackish than @Html.Raw("…")

@if (condition) { 
    @:<a href="#"> 
}
<div>
    <h1>Header</h1>
    <span>Subheader</span>
    <p>Lorem ipsum</p>
</div>
@if (condition) { 
    @:</a>
}

related: What does @: mean in ASP.net MVC Razor?

like image 64
dwtm.ts Avatar answered Jan 20 '26 21:01

dwtm.ts


I feel like this is cheating, smelly and hack'ish but:

@if (condition) { @Html.Raw("<a href='#'>") }
    <div>
        <h1>Header</h1>
        <span>Subheader</span>
        <p>Lorem ipsum</p>
    </div>
@if (condition) { @Html.Raw("</a>") }
like image 40
mxmissile Avatar answered Jan 20 '26 23:01

mxmissile



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!