I am trying to create a logout button through dynamically generated HTML (string).
htmlGen = "<div class=\"issue\" style=\"float:right; width:70%;\">";
htmlGen += "Welcome, " + Page.User.Identity.Name.ToString() + " (<a href=\"#\" id=\"LogOutLink\" onclick=\"<%=LogOut_OnClick%>\"> logout </a>)";
As you can see, the logout method is in the server code:
public void LogOut_OnClick(object sender, EventArgs args) {
FormsAuthentication.SignOut();
string htmlGen = "<div class=\"issue\" style=\"float:right; width:45%;\">";
htmlGen += "<a style=\"color:White;\" href=\"/Login.aspx\">Login</a>";
htmlGen += " | <a style=\"color:White;\" href=\"/Accounts/SignUp.aspx\">Register</a>";
this.Literal1.Text = htmlGen + "</div>";
FormsAuthentication.RedirectToLoginPage();
}
No matter what i do, this doesn't seem to work (won't fire, won't log out, etc). Is there something about doing this as an HTML string to a literal that is causing this?
Would somebody mind telling me how to do this?
Thanks!
First, you are trying to do a post back using a javascript client side event (onlick="..."). Also, using ASP.net directive <%= %> in the code behind won't work. In fact, if you check right now in your rendered HTML on your browser, you probably have something along these lines:
onclick="<%=LogOut_OnClick%>"
Anyway, if you can't generate this code in your aspx file, you should consider replacing this by the __dopostback javascript function (http://stackoverflow.com/questions/3591634/how-to-use-dopostback):
[...] htmlGen += "onclick=\"__dopostback('" + LogOutButton.ID + "')\""; [...]
However, you should really consider putting all this code inside your aspx file in a way or another. Here's how I would do it:
Welcome, <%= UserName %> (<asp:LinkButton ID="LogoutButton" Text="Logout" runat="server"/>)