Chris N.P.
Chris N.P.

Reputation: 783

Displaying the Name of an HTML Control (Input with Submit type) in ASP.NET Web Forms

For example I have 2 input submit buttons in my aspx page:

<input runat="server" name="btnSubmit" id="btnSubmit" value="Submit" type="submit" OnServerClick="ibtn_Click" />
<input runat="server" name="btnCancel" id="btnCancel" value="Cancel" type="submit" OnServerClick="ibtn_Click" />

From code behind how can I check if the button that the user click is Submit or Cancel?

I'm new to Web Forms.

Upvotes: 0

Views: 301

Answers (2)

Olrac
Olrac

Reputation: 1537

Yes!, It is possible to use 1 method/function to 2 or more buttons....And also using 1 method/function you can determine the button you use if it is submit or cancel..

*.asp

<input type="submit" value="Submit" ID="Button1" runat="server" Text="Submit" OnServerClick="Button1_Click" />
<input type="submit" value="Cancel" ID="Button2" runat="server" Text="Cancel" OnServerClick="Button1_Click" />

*.cs(codebehind)

protected void Button1_Click(object sender, EventArgs e)
    {
        System.Web.UI.HtmlControls.HtmlInputButton btn = sender as System.Web.UI.HtmlControls.HtmlInputButton;

        if (btn.Value == "Submit")
        {
            // statements
        }
        else if (btn.Value == "Cancel")
        {
            // statements
        }
    } 

Upvotes: 0

HTML

OnServerClick="ibtn_Click(this)" 

js

function ibtn_Click(el){
   if(el.id == 'btnSubmit'){ // code here for Submit button}
   else if(el.id == 'btnCancel'){ // code here for Cancel button}
}

Updated after OP's comment.

You make different function for both the buttons and keep the common code if any in the another function and call this function in both function to be used.

Example

function common_code (){ //common code for both functions }
function btnSubmit (){
  // code here for Submit button and call 
  common_code ();
}
function btnCancel (){
  // code here for Cancel button and call 
  common_code ();
}

HTML

<input runat="server" name="btnSubmit" id="btnSubmit" value="Submit" type="submit" OnServerClick="btnSubmit" />
<input runat="server" name="btnCancel" id="btnCancel" value="Cancel" type="submit" OnServerClick="btnCancel" />

Upvotes: 1

Related Questions