mmmoustache
mmmoustache

Reputation: 2323

Detect which form has been submitted in C#/ASP.NET

I have two forms on the same webpage and I would like to detect which one was submitted upon a post event and show a different message dependant on the submitted form.

I have seen a few examples where people have detected this based on which submit button was clicked, but in my case the form could be submitted by simply pressing enter. Is it possible to detect which form was submitted based on the form name/id? If this can not be done, what would be the best approach for this?

Here is my code in it's simplest form, I think the syntax I've used is for when using submit buttons, but I included it just incase I was wrong:

<form method="post" name="form1" id="form1">
    <input type="text" name="textbox1" />
</form>

<form method="post" name="form2" id="form2">
    <input type="text" name="textbox2"  />
</form>

if(IsPost){
    if(Request["submit"] == "form1"){
        <p>Form 1 was submitted</p>
    }else if(Request["submit"] == "form2"){
        <p>Form 2 was submitted</p>
    }
}

Upvotes: 2

Views: 3604

Answers (1)

RononDex
RononDex

Reputation: 4183

You could place a hidden field in each form that holds a unique name for the form:

<form method="post" name="form1" id="form1">
    <input type="text" name="textbox1" />
    <input type="hidden" name="Form1Submitted" value="true" />
</form>

<form method="post" name="form2" id="form2">
    <input type="text" name="textbox2"  />
    <input type="hidden" name="Form2Submitted" value="true" />
</form>

Then you could check it in your codebehind like this:

if(IsPost){
    if(Request["Form1Submitted"] == "true"){
        <p>Form 1 was submitted</p>
    }else if(Request["Form2Submitted"] == "true"){
        <p>Form 2 was submitted</p>
    }
}

Upvotes: 3

Related Questions