Saturday, 24 January 2009

Invoking a button click event in ASP.NET when the button wasn’t clicked, but you want the code to run anyway.

I have just had a situation where I need a button click to invoke inside a control that part of a COTS product. On our login page, there’s the username and password fields, along with a login LinkButton control.

When the login button is clicked, or the user hits ENTER, then the login button click event handler invokes as it should.  However, on some mobile browsers and using my Dell Biometric reader for authentication, the button click is not performed because it’s doing a direct submit on the form – hence, the login button click event handler doesn’t invoke, therefore, the user cannot login.

After a bit of research, it seems there’s no easy way to just invoke a click on a button.  People suggest that I refactor the control so that it has a public “Login” method… however, this is a Community Server control… I don’t really want to customise the codebase for a product, for something so simple.

So the following does the trick via reflection

void Page_PreRender(object sender, EventArgs args) 
{
if (Page.IsPostBack
&& Request.Form["__EVENTTARGET"] != loginButton.UniqueID)
Login();
}

private void Login()
{
// Manually invoke login button click
Type t = loginButton.GetType();
object[] p = new object[1];
p[0] = EventArgs.Empty;
MethodInfo m = t.GetMethod("OnClick",
BindingFlags.NonPublic
| BindingFlags.Instance);
m.Invoke(loginButton, p);
}



Not the cleanest and most optimal solution, but it gets the job done!