Search code examples
asp.netpostrazorasp.net-webpages

How to constrain a POST call to just one submit button in ASP.NET Web pages?


I have two buttons in the same page (ASP.NET Web Pages & Razor syntax), how do I check which button I clicked?

so far I have:

if (IsPost)
{   
   //code block here 
}

and:

<input type="submit" value="Update" class="submit" id="btnUpdate" />
<input type="submit" value="Clear" class="submit" id="btnClear" />

but the problem is that the above code executes when either button is clicked. I want only btnUpdate to execute the code block.

Note: This is in a Web Pages application, not ASP.NET MVC.

ASP.NET docs shows an example for checking which textbox is empty to determine the action when a different button is clicked... that's not what I'm looking for.


Solution

  • Attach a name attribute to the input buttons:

    <input type="submit" value="Update" class="submit" id="btnUpdate" name="update" />
    <input type="submit" value="Clear" class="submit" id="btnClear" name="clear" />
    

    Then check which one was submitted via this code:

    if (IsPost) {
        if (Request.Form["clear"] != null) {
            //when clear clicked
        }
        else if (Request.Form["update"] != null) {
            //when update clicked
        }
    }