What is the best way to pass a variable from an OnClick event. To elaborate I would like to bind some data to the button and then when that button is pressed I would like to pass that data back to the code behind and do something cool with it.
I have found several ways of doing this, passing a commandParamter, add a button tag and use that. I wonder what is considered the best practice for this problem? Also am i looking at the problem wrong? Should I not try to pass a variable on click but do something else?
markup
<asp:button text="test" id="btnTest" runat="server"/>
codebehind
Protected Sub btnTest_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnTest.Click
'do something cool
End Sub
It doesn’t sound like you’re really “passing” a variable to the button’s click event. You’re simply (and correctly) referencing the current value in the textbox by accessing
test.Text. For example, assuming you have a label on your form namedresultLabel:Of course realistically you would use a
RequiredFieldValidatoror have a better way of displaying errors to the user instead of re-using the same label.This approach is fine. Once you’re familiar with this style you may choose to implement the Model-View-Presenter (MVP) pattern. A good project to look at is ASP.NET Web Forms MVP. Alternately, Microsoft offers a different flavor of ASP.NET, namely ASP.NET MVC (Model-View-Controller).