tags:

views:

223

answers:

5

I have two buttons on my MVC form:

<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

From my Controller action how do I know which one have been pressed?

+3  A: 
<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

And in your controller action:

public ActionResult SomeAction(string submit)
{
    if (!string.IsNullOrEmpty(submit))
    {
        // Save was pressed
    }
    else
    {
        // Process was pressed
    }
}
Darin Dimitrov
A: 

Can you not find out using Request.Form Collection? If process is clicked the request.form["process"] will not be empty

chugh97
+1  A: 

I suggest looking at this post. I like the second solution since you are programming the logic in the controller and not in the view.

HTH, indyfromoz

indyfromoz
The second solution uses the same `name` attribute for both submit buttons and inspects the `value` attribute in the controller which could be problematic. Imagine for example a Chinese web site. IMHO it is better to use the `name` attribute in the controller.
Darin Dimitrov
+1  A: 

Name both your submit buttons the same

<input name="submit" type="submit" id="submit" value="Save" />
<input name="submit" type="submit" id="process" value="Process" />

Then in your controller get the value of submit. Only the button clicked will pass it's value.

public ActionResult Index(string submit)
        {
            Response.Write(submit);
            return View();
        }

You can of course assess that value to perform different operations with a switch block.

public ActionResult Index(string submit)
        {
            switch (submit)
            {
                case "Save":
                    // Do something
                    break;
                case "Process":
                    // Do something
                    break;
                default:
                    throw new Exception();
                    break;
            }

            return View();
        }
WDuffy
Beware the issues that localisation could bring to this solution, to which Darin's solution is not susceptable.
Richard Szalay
A: 

Martin wrote a neat post about this.

Arnis L.