user3530169 user3530169 - 1 year ago 99
HTML Question

Creating an HTML anchor to run a C# function programatically

I am trying to create a "Select User" page, which will dynamically pull user data from a database, and then generate a link for each user found in the database to select from. When the link is clicked, it will call a C# function to create a cookie and redirect the user.

The code correctly pulls the users from the database and generates the links, however the links do not function. Here is the C# code which generates the links:

String sqlStatement = "SELECT * FROM TUsers";
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand comm = new SqlCommand(sqlStatement, conn);
SqlDataReader Reader = comm.ExecuteReader();
while (Reader.Read())
container.InnerHtml += "<a runat='server' href='#' onServerClick='UserButton_Click' > <div class='users'> <p>" + Reader["FirstName"] + " " + Reader["LastName"] + "</p> </div> </a>";

Here is the HTML Source code on the generated page:

<div id="container"><a runat='server' href='#' onServerClick='UserButton_Click' > <div class='users'> <p>User 1</p> </div> </a>

The backend C# code for when the link is clicked is irrelevant for this question. Using breakpoints, the function that is supposed to be called is never called to begin with.

I have tried using HTML anchors with onServerClick, which so far is not actually running the proper function, as well as attempting to use
items, however from what I could tell, they were not parsing correctly due to being generated via container.InnerHtml.

Answer Source

You could use a ListView control to get what you want:

<asp:ListView ID="lvUsers" runat="server">
            <asp:LinkButton ID="lnkUser" runat="server" OnClick="lnkUser_Click" Text='<%# Eval("FirstName") + " " + Eval("LastName") %>' />

The data source of the ListView could be set like this:

using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (SqlCommand comm = new SqlCommand("SELECT * FROM TUsers", conn))
    SqlDataAdapter dataAdapter = new SqlDataAdapter(comm);
    DataSet ds = new DataSet();
    dataAdapter.Fill(ds, "Users");
    lvUsers.DataSource = ds.Tables[0];

And the event handler would be similar to what you already have:

protected void lnkUser_Click(object sender, EventArgs e)
    // Process user data and redirect
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download