Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect which submit button was clicked in asp.net (mvc)

I've read plenty of answers that use the value of submit type input, but my collection of input buttons need to all have the same text. Others use Javascript, and I'm trying to avoid that as well.

<input type="submit" value="Press This" name="submitButton" />

Doesn't work because they all need to be named 'Press This'.

<button type="submit" value="12" name="submitButton">Press This</button>

Doesn't work because it doesn't post the value.

Is there some way to make the <button> submit it's value or to change the text of the <input type="submit"> so they all say the same on the page while having different values? Or possibly even hiding the numeric value in the value attribute of the input element and then just removing the "Press This" before using the value?

Perhaps using <input type="image" value="12" /> with a image that says "Press This"?

Edit: Tried the <input type="image"> and it doesn't work. It'll submit the form, but it doesn't use the name attribute to go to the correct action on the controller.

Edit2: I should also add, the number of submit buttons is dynamic and thus I cannot give them all different names and then see which parameter in the controller had a value passed to it. Unless there is some way to do this for a unknown number of buttons...

like image 767
Lawtonfogle Avatar asked Aug 19 '14 20:08

Lawtonfogle


1 Answers

your buttons should look like this:

<button name="button" value="12">Press This</button>
<button name="button" value="13">Press That</button>

then just get them in the action

public ActionResult MyAction(string button)
{
    if (button == "12"){
        //Do this
    }

    if (button == "13"){
        //Do that
    }
}
like image 59
Wahid Bitar Avatar answered Oct 02 '22 19:10

Wahid Bitar