Search code examples
c#asp.netlinkbutton

How can i make the "link_click" work without affecting the required field validators?


To elaborate my question, I have shopping cart website. Also I have textboxes like username, address, contact etc. All of those has the required field validator. However I also do have the "view profile" and "log out" link button on the page. When I try to clike those links, its not letting me because the required fields are not filled up. Is there any trick I can do with this? Thank you for any answers :)

Here is my code.

<asp:TextBox ID="txtCustomerName" runat="server" Width="231px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
    ErrorMessage="Customer Name is Required." ForeColor="Red" ControlToValidate="txtCustomerName"
    ></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
    <td align="left">
        Phone No:
    </td>
</tr>
<tr>
    <td>
        <asp:TextBox ID="txtCustomerPhoneNo" runat="server" Width="231px" 
            MaxLength="11"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ErrorMessage="Phone Number is required." ForeColor="Red" ControlToValidate="txtCustomerPhoneNo"
            ></asp:RequiredFieldValidator>
    </td>
</tr>
<tr>
    <td align="left">
        EmailID:
    </td>
</tr>
<tr>
    <td>
        <asp:TextBox ID="txtCustomerEmailID" runat="server" Width="231px"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
            ErrorMessage=" Email Address is Required." ForeColor="Red" ControlToValidate="txtCustomerEmailID"
            ></asp:RequiredFieldValidator>
    </td>

and here is my link codes.

 protected void link_ViewProfile_Click(object sender, EventArgs e)
    {
        Response.Redirect("viewprofile.aspx");
    }

    protected void link_Logout_Click(object sender, EventArgs e)
    {
        Session.Clear();
        Response.Redirect("Home.aspx");
    }

Solution

  • For those link button on which you want to run validation add validationgroup attribute. For Example

    <asp:button id="Button2" 
      text="Validate" 
      causesvalidation="true"
      validationgroup="LocationInfoGroup"
      runat="Server" />
    

    Also add validationgroup attribute in RequiredFieldValidator

    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                ErrorMessage="Phone Number is required." ForeColor="Red" ControlToValidate="txtCustomerPhoneNo"
    validationgroup="LocationInfoGroup"
                ></asp:RequiredFieldValidator>