Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the onClick event for Hyperlink using C# code?

Tags:

c#

asp.net

I am trying to add a condition for a hyperlink that I have in my page.

Instead of just using a particular link like: <a href="help/Tutorial.html">Tutorial</a> I want to display different pages for different users. For example, if the user is logged in as Admin, they will be presented with different link than regular users.

I have modified my hyperlink as: <a onclick="displayTutorial_Click">Tutorial</a>

and added this code:

    protected void displayTutorial_Click(object sender, EventArgs e)
    {
        // figure out user information
        userinfo = (UserInfo)Session["UserInfo"];

        if (userinfo.user == "Admin")

            System.Diagnostics.Process.Start("help/AdminTutorial.html");

        else

            System.Diagnostics.Process.Start("help/UserTutorial.html");            
    }

But this didn't work. Can anyone please help me to figure out how I can make the Tutorial link work properly? Thank you a lot in advance!!!

like image 904
AlwaysANovice Avatar asked Nov 30 '22 15:11

AlwaysANovice


1 Answers

The onclick attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)

What you want is a server-side control, like the LinkButton:

<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>

This has an OnClick attribute that will call the method in your code behind.

Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton control in the code behind.

protected void Page_Load(object sender, EventArgs e)
{
    userinfo = (UserInfo)Session["UserInfo"];

    if (userinfo.user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

Really, it would be best to check that you actually have a user first.

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}
like image 134
Jeremy Wiggins Avatar answered Dec 02 '22 04:12

Jeremy Wiggins