[英]How to set html link <a href> dynamically using C#
我的網絡應用程序中有一個這樣的菜單
<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>
如果某些特殊條件成立,我想動態設置這些href鏈接。
我嘗試了以下方法:
HTML代碼
<li><a runat="server" id="toSettings" onserverclick="toSettings_ServerClick">Settings</a></li>
C#代碼
protected void toSettings_ServerClick(object sender, EventArgs e)
{
if (condition)
toSettings.HRef = "http://localhost:52451/Voronezh/Settings.aspx";
else
{...}
}
但它不起作用:我停留在同一頁面上,而不是移至“設置”頁面。
哪里有錯? 應該改變什么?
提前致謝。
更改HRef
在這里沒有多大作用-它更改了鏈接,對頁面沒有任何直接影響。 試試Response.Redirect ,我想這就是您要尋找的。 即:
// inside the if statement
Response.Redirect("Settings.aspx"); // note - this is the local path
假設這是ASP.NET C#
從HttpResponse重定向的方法應該是您想要的。
參考:
https://msdn.microsoft.com/zh-CN/library/a8wa7sdt(v=vs.110).aspx
如果要在后面的代碼中動態構建菜單,則可能應在ASPX中使用<asp:Literal ID="menu" runat="server"/>
標記,並將其填充到Page_Load
事件中,例如
if (!Page.IsPostBack) {
menu.Text = GenerateMenu();
}
private string GenerateMenu() {
if (yourcondition) {
return "<div><ul><li><a href="...."></a></li></ul></div>";
} else {
}
}
進行回發,執行邏輯然后進行重定向的另一種方法是將鏈接標記更改為超鏈接控件,在頁面加載時執行邏輯,並動態設置屬性。
HTML:
<asp:HyperLink id="toSettings" Text="Settings" runat="server"/>
背后的代碼
protected void Page_Load(object sender, EventArgs e) {
toSettings.NavigateUrl = "http://localhost:52451/Voronezh/Settings.aspx";
}
這樣,您甚至可以根據需要更改文本(使用toSettings.Text = "Text to display";
)或可見性(使用toSettings.Visible = false;
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.