Search code examples
asp.net.nethyperlinkhref

Conditional hyperlink is not working in asp.net


I used hyperlinks in menu section in my asp.net application. I want to redirect user to the specific page based on the type of user. Here is the code I am using

<li>
<a id="store" href= "<%# (Session["Coupon"] == "Active") ? "url1.aspx": "url2.aspx" %>"></a>
</li>

If Session["Coupon"] == "Active" then user should redirect to "url1.aspx" else redirect to "url2.aspx".

Can anyone please help me how to give condition to hyperlink to get redirected?


Solution

  • Actually you got confused "#" with "=". Here you have done the following:-

    <li>
    <a id="store" href= "<%# (Session["Coupon"] == "Active") ? "url1.aspx": "url2.aspx" %>"></a>
    </li>
    

    Note that you have used "#" hash tag in embedded code block, It is a binding expression and usually used when you try to bind things up in html. For e.g. <%# Eval("Name") %>. Now here we don't need to bind thing rather write things in html so kindly use following expression:-

    <li>
    <a id="store" href= "<%= (Session["Coupon"] == "Active") ? "url1.aspx": "url2.aspx" %>"></a>
    </li>
    

    You just need to replace "#" with "=" that all you need to do.

    For more information kindly refer this thread Symbols Used in Embedded Code Block.