by Simon Deshaies
12. January 2009 15:07
Passing value from a aspx form to code behind is a challenge the APS.NET developer faces often. I my self found very creative ways to do so over the years. One of my favored for a log time was to use the OnClientClick event to set a hidden value field before the form was submitted to the server.
Yesterday I started to use User Controls and I could not have the JavaScript function in each control, and certainly not refer to the parent. I would of just broke the reusability of the control. That's when I discovered this quite cool property of the Button and LinkButton. It was certainly not meant to be use in this way but it's much more elegant then the HiddenField one.
Instead of using the OnClientClick event I set the value of the CommandArgument property when rendering the page as follows:
ListView Item:
<asp:LinkButton runat="server"
Text='<%# Eval("SomeName") %>'
CommandArgument='<%# Eval("SomeId") %>'
OnClick="Delete" ID="DeleteLinkButton" />
So when the server receives the form your button event is triggered:
protected void Delete(object sender, EventArgs e)
{
Object Obj = ((LinkButton)sender).CommandArgument;
//Do something with Obj;
}
So here it is 2 steps to get the value from the LinkButton. In the Delete method I cast the sender to LinkButton so I can access the CommandArgument property.
Let me know what you think.