Reputation: 23
I have a menu in my web application like this
<div>
<ul>
<li><a href="http://localhost:52451/Voronezh/Settings.aspx">Settings</a</li>
<li><a href="http://localhost:52451/LoginPages/Welcome.aspx">Log out</a</li>
</ul>
</div>
I would like to set these href links dynamically if some special condition is true.
I've tried the following:
HTML code
<li><a runat="server" id="toSettings" onserverclick="toSettings_ServerClick">Settings</a></li>
C# code
protected void toSettings_ServerClick(object sender, EventArgs e)
{
if (condition)
toSettings.HRef = "http://localhost:52451/Voronezh/Settings.aspx";
else
{...}
}
but it doesn't work: I stay on the same page instead of moving to the Settings page.
Where is a mistake? What should be changed?
Thanks in advance.
Upvotes: 1
Views: 23956
Reputation: 306
Another alternative to doing a postback, executing the logic, and then doing a redirect would be to change the link tag to the hyperlink control, execute the logic on page load, and set the properties dynamically.
HTML:
<asp:HyperLink id="toSettings" Text="Settings" runat="server"/>
Code Behind
protected void Page_Load(object sender, EventArgs e) {
toSettings.NavigateUrl = "http://localhost:52451/Voronezh/Settings.aspx";
}
This way you could even change the text (use toSettings.Text = "Text to display";
) or the visibility (use toSettings.Visible = false;
) if needed.
Upvotes: 1
Reputation: 2929
If you want to build your menu dynamically in code behind you should probably use a <asp:Literal ID="menu" runat="server"/>
tag in ASPX and fill it in the Page_Load
event like
if (!Page.IsPostBack) {
menu.Text = GenerateMenu();
}
private string GenerateMenu() {
if (yourcondition) {
return "<div><ul><li><a href="...."></a></li></ul></div>";
} else {
}
}
Upvotes: 1
Reputation: 1865
Changing the HRef
won't do much here - it changes the link, it doesn't have any direct effect on the page. Try Response.Redirect, I think this is what you're looking for. I.e:
// inside the if statement
Response.Redirect("Settings.aspx"); // note - this is the local path
Upvotes: 4
Reputation: 381
Assuming this is ASP.NET C#
Redirect method from the HttpResponse should be what you are looking for.
Reference:
https://msdn.microsoft.com/en-us/library/a8wa7sdt(v=vs.110).aspx
Upvotes: 1