Rules

Secret ingredients to quality software

Do you know not to use LinkButton?

Last updated by Tiago Araujo on 01 Sep 2016 06:06 pm (almost 5 years ago) See History

If we want to refresh and data bind the same page from client side, we can use the javascript function calls "__doPostBack". We shouldn't fire this post back in LinkButton. Otherwise, there will be an error.

Figure: Right click the link with __doPostBack event

Figure: New window with incorrect URL

ASPX:
<asp:Panel runat="server" ID="mUpdatePanel" OnLoad="mUpdatePanel_Load">
 <asp:Label runat="server" ID="lblTime" />
 <br />
 <asp:GridView ID="gvList" runat="server" AutoGenerateColumns="false">
 <Columns>
 <asp:BoundField DataField="ID" HeaderText="ID" />
 </Columns>
 <Columns>
 <asp:BoundField DataField="Name" HeaderText="Name" />
 </Columns>
 </asp:GridView>
 <br />
 ID:<asp:TextBox ID="txtID" runat="server"/>
 Name:<asp:TextBox ID="txtName" runat="server"/>
</asp:Panel>
C#:
protected void mUpdatePanel_Load(object sender, EventArgs e)
{
 lblTime.Text = DateTime.Now.ToLongTimeString();
 ArrayList mList = (ArrayList)ViewState["List"];
 if (txtName.Text.Length > 0)
 {
 Client mClient = new Client();
 mClient.ID = Int32.Parse(txtID.Text);
 mClient.Name = txtName.Text;
 mList.Add(mClient);
 ViewState["List"] = mList;
 gvList.DataSource = mList;
 gvList.DataBind();
 }
}

Sample Code

<a href="javascript:__doPostBack('mUpdatePanel','');">Refresh</a>

Bad Code

<input type="button" onclick="javascript:__doPostBack('mUpdatePanel','');" value="Refresh" />

Good Code

We have a program called SSW Code Auditor to check for this rule.

Adam CoganAdam Cogan

We open source. This page is on GitHub