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.
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. Ie:
// inside the if statement
Response.Redirect("Settings.aspx"); // note - this is the local path
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
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 {
}
}
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.
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.