Monday, May 18, 2009

Which button was clicked in the ASP.NET MVC View?

In an ASP.NET MVC view you might have multiple "submit" buttons inside a <form> such as:

<% using (Html.BeginForm()) {%>
       <input type="submit" value="Create" name="create" />
       <input type="submit" value="Cancel" name="cancel" />
<% } %>

The Html helper extension method BeginForm() will emit an opening and closing <form> tag that encloses the input fields.

Your controller that accepts the POST verb will look something like this:

        public ActionResult Create(FormCollection collection)
                string create = Request.Form["create"];
                string cancel = Request.Form["cancel"];

                return RedirectToAction("Index");
                return View();

If the Create button was clicked then the create variable will be set to "Create" (because "Create" is the value set to the input named "create") and the cancel button will be set to null. The opposite is true if the Cancel button is clicked.


  1. This almost works but if I have a textbox with some jQuery validation for some reason it 'loses' the value for the button pressed. It's really annoying!

  2. I tried this and it definitely returns the value of the button clicked. However, I am doing client-side validation using and when the Cancel button is clicked it insists on having valid data before posting back, even when I have causesvalidation set to false.
    <input type="submit" value="Cancel" name="cancel" causesvalidation="false" />
    That's not of much use for a cancel button, since why would I want valid data on a cancel?

  3. Robert - in that case you would completely remove the causesvalidation attribute instead of setting it to false.